<!DOCTYPE html>

<html lang="en">
<!-- documentation for s7 -->

<head>
<title>s7</title>

<style type="text/css">
	EM.red {color:red; font-style:normal}
	EM.normal {font-style:normal}
	EM.redb {color:red; font-weight: bold; font-style: normal}
        EM.error {color:chocolate; font-style:normal}
	EM.emdef {font-weight: bold; font-style: normal}
	EM.green {color:green; font-style:normal}
	EM.big {font-size: 20px;
	        font-style: normal;
		}
	EM.bigger {font-size: 30px;
                   font-style: normal;
		   }
        EM.def {font-style: normal}

	H1 {text-align: center}
	UL {list-style-type: none}

	A {text-decoration:none}
	A:hover {text-decoration:underline}
	A.quiet {color:black; text-decoration:none}
	A.quiet:hover {text-decoration:underline}

	A.def {font-weight: bold; 
	       font-style: normal; 
	       text-decoration:none; 
	       text-color:black;
	       }

        PRE.indented {padding-left: 1.0cm;}

	DIV.indented {background-color: #F8F8F0; 
	              padding-left: 0.5cm; 
	              padding-right: 0.5cm; 
		      padding-top: 0.5cm; 
		      padding-bottom: 0.5cm;
		      margin-bottom: 0.5cm;
		      border: 1px solid gray;
		      -moz-border-radius: 20px;
		      -webkit-border-radius: 20px;
		      }

	DIV.obsolete {background-color: #F2F2F2; 
		      border: 1px solid black;
	              padding-left: 0.5cm; 
	              padding-right: 0.5cm; 
		      padding-top: 0.5cm; 
		      padding-bottom: 0.5cm;
		      }
        DIV.header {margin-top: 60px;
	            margin-bottom: 30px;
	            border: 4px solid #00ff00; /* green */
		    background-color: #eefdee; /* lightgreen */
		    padding-left: 30px;
	           }
        DIV.topheader {margin-top: 10px;
	            margin-bottom: 40px;
	            border: 4px solid #00ff00; /* green */
		    background-color: #f5f5dc; /* beige */
		    font-family: 'Helvetica';
		    font-size: 30px;
		    text-align: center;
		    padding-top: 10px;
		    padding-bottom: 10px;
	           }
        DIV.separator {margin-top: 30px;
	               margin-bottom: 10px;
	               border: 2px solid #00ff00; /* green */
		       background-color: #f5f5dc; /* beige */
		       padding-top: 4px;
		       width: 30%;
		      -moz-border-radius: 4px;
		      -webkit-border-radius: 4px;
		      } 

	DIV.bluishbordered {background-color: #f2f4ff;
	                   border: 1px solid #000000;
			   padding-left: 10px;
			   padding-right: 10px;
			   padding-top: 10px;
			   padding-bottom: 10px;
			   }
	DIV.brownishbordered {background-color: #fbfbf0;
	                   border: 1px solid #000000;
			   padding-left: 10px;
			   padding-right: 10px;
			   padding-top: 10px;
			   padding-bottom: 10px;
			   }
        BODY.body {background-color: #ffffff;    /* white */
	           margin-right: 20px;
	           margin-left: 20px; 
                   }
        DIV.orange {background-color: #ffa500; /* orange */
		   padding-left: 6px;
		   padding-right: 6px;
		   padding-top: 4px;
		   padding-bottom: 4px;
	           border: 4px solid #000000;
		   font-family: 'Helvetica';
		   font-size: 12px;
	           font-weight: bold;
		   text-align: center;
		   margin-left: 0.5cm;
		   margin-right: 1.0cm;
		   float: right;
		   -moz-border-radius: 8px;
		   -webkit-border-radius: 8px;
		   }
        DIV.listener {background-color: #f0f8ff;
	              font-family: 'Monospace';
		   padding-left: 6px;
		   padding-right: 6px;
		   padding-bottom: 4px;
		   margin-left: 1.0cm;
		   margin-right: 4.0cm;
	              border: 2px solid #a0a0a0;
		      }
        LI.li_header {padding-top: 20px;}
</style>
</head>
<body class="body">

<!-- INDEX s7doc:s7 scheme -->


<div class="topheader" id="s7doc">s7
</div>


<p>s7 is a Scheme implementation intended as an extension language
for other applications, primarily Snd and Common Music.  It exists as just two files, s7.c and
s7.h, that want only to disappear into someone else's source tree.  There are no libraries,
no run-time init files, and no configuration scripts.
It can be built as a stand-alone
interpreter (see <a href="#repl">below</a>).  s7test.scm is a regression test for s7.
A tarball is available: ftp://ccrma-ftp.stanford.edu/pub/Lisp/s7.tar.gz.  
</p>

<p>
s7 is the default extension language of Snd and sndlib (http://ccrma.stanford.edu/software/snd/),
and Rick Taube's Common Music (commonmusic at sourceforge).  There are X, Motif, Gtk, and openGL bindings
in libxm in the Snd tarball, or at ftp://ccrma-ftp.stanford.edu/pub/Lisp/libxm.tar.gz.
If you're running s7 in a context
that has getenv, file-exists?, and system, you can use s7-slib-init.scm
to gain easy access to slib.  This init file is named "s7.init" in the slib distribution.
</p>

<p>Although it is a descendant of tinyScheme, s7 is closest as a Scheme dialect to Guile 1.8.
I believe it is compatible with <a href="#s7vsr5rs">r5rs</a> and <a href="#r7rs">r7rs</a>:  you can just ignore all the additions discussed in this file.
It has continuations, 
ratios, complex numbers,
macros, keywords, hash-tables, 
multiprecision arithmetic,
generalized set!, unicode, and so on.
It does not have syntax-rules or any of
its friends, and it does not think there is any such thing
as an inexact integer.  
</p>

<p>This file assumes you know about Scheme and all its problems,
and want a quick tour of where s7 is different.  (Well, it was quick once upon a time).
The main difference: if it's in s7, it's a first-class citizen of s7, and that includes
macros, environments, and syntactic forms.
</p>

<br>
<blockquote>
<div class="indented">
<p>I originally used a small font for scholia, but now I have to squint
to read that tiny text, so less-than-vital commentaries are shown in the normal font, but 
indented and on a sort of brownish background.
</p>
</div>
</blockquote>
<br>


<div class="orange">
<p>Danger!</p>
<p>Men Working</p>
<p>in Trees</p>
</div>

<ul>
  <li><a href="#multiprecision">multiprecision arithmetic</a>
  <li><a href="#math">math functions</a>
  <li><a href="#define*">define*, named let*</a>
  <li><a href="#macros">define-macro</a>
  <li><a href="#pws">procedure-setter</a>
  <li><a href="#generalizedset">generalized set!</a>
  <li><a href="#multidimensionalvectors">multidimensional vectors</a>
  <li><a href="#hashtables">hash tables</a>
  <li><a href="#environments">environments</a>
  <li><a href="#multiplevalues">multiple-values</a>
  <li><a href="#callwithexit1">call-with-exit</a>
  <li><a href="#format1">format</a>
  <li><a href="#hooks">hooks</a>
  <li><a href="#procedureinfo">procedure info</a>
  <li><a href="#evalstring">eval</a>
  <li><a href="#IO">IO and other OS functions</a>
  <li><a href="#errors">errors</a>
  <li><a href="#autoload">autoload</a>
  <li><a href="#constants">define-constant, symbol-access</a>
  <li><a href="#miscellanea">miscellaneous:</a> 

  <ul>
    <li><a href="#loadpath">*load-path*</a>, <a href="#featureslist">*features*</a>, <a href="#sharpreaders">*#readers*</a>
    <li><a href="#makelist">make-list</a>, <a href="#charposition">char-position</a>, <a href="#keywords">keywords</a>
    <li><a href="#symboltable">symbol-table</a>, <a href="#s7help">help</a>, <a href="#s7gc">gc</a>, <a href="#morallyequalp">morally-equal?</a>
    <li><a href="#s7vsr5rs">r5rs</a>, <a href="#r7rs">r7rs</a>, <a href="#circle">circular lists</a>, <a href="#legolambda">legolambda</a>, etc...
    </ul>

  <li class="li_header"><a href="#FFIexamples">FFI examples</a>
  <ul>
      <li><a href="#repl">read-eval-print loop (and emacs)</a>
      <li><a href="#defun">define a function with arguments and a returned value, and define a variable </a>
      <li><a href="#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
      <li><a href="#juce">C++ and Juce</a>
      <li><a href="#sndlib">load sndlib using the Xen functions and macros</a>
      <li><a href="#pwstype">add a new Scheme type and a procedure with a setter</a>
      <li><a href="#functionportexample">redirect display output to a C procedure</a>
      <li><a href="#extendop">extend a built-in operator ("+" in this case)</a>
      <li><a href="#definestar1">C-side define* (s7_define_function_star)</a>
      <li><a href="#definemacro1">C-side define-macro (s7_define_macro)</a>
      <li><a href="#definegeneric">define a generic function in C</a>
      <li><a href="#signal">signal handling (C-C to break out of an infinite loop)</a>
      <li><a href="#vector">direct multidimensional vector element access</a>
      <li><a href="#notify">notification in C that a Scheme variable has been set!</a>
      <li><a href="#namespace">Load C defined stuff into a separate namespace</a>
      <li><a href="#Cerrors">Error handling in C</a>
      <li><a href="#closure">Closure defined in C</a>
      <li><a href="#testhook">Hooks in C and Scheme</a>
      <li><a href="#dload">Load a C module dynamically</a>
      <li><a href="#gmpex">gmp and friends</a>
      <li><a href="#gtkrepl">Gtk-based REPL</a>
      <li><a href="#gtkschemerepl">Gtk/Scheme-based REPL</a>
      <li><a href="#replrescue">begin_hook to the rescue!</a>
      <li><a href="#glistener">glistener.c</a>
      <li><a href="#gdb">gdb</a>
  </ul>

  <li class="li_header"><a href="#s7examples">s7 examples</a>
  <ul>
      <li><a href="#lint">lint.scm</a>
      <li><a href="#cload">cload.scm</a>
  </ul>
</ul>


<div class="header" id="multiprecision"><h4>multiprecision arithmetic</h4></div>

<p>All numeric types, integers, ratios, reals, and complex numbers are supported.
The basic integer and real
types are defined in s7.h, defaulting to long long int and double.  
A ratio consists of two integers, a complex number two reals.
pi is predefined, as are
most-positive-fixnum and most-negative-fixnum.
s7 can be built with multiprecision support 
for all types,  using the gmp, mpfr, and mpc libraries (set WITH_GMP to 1 in s7.c).  
If multiprecision arithmetic is
enabled, the following functions are included: bignum, and bignum?, and the variable *bignum-precision*.
<em class=def id="bignumprecision">*bignum-precision*</em>, defaults to 128; it sets the number of bits each float takes.
pi automatically reflects the current *bignum-precision*:
</p>

<pre class="indented">
&gt; pi
3.141592653589793238462643383279502884195E0
&gt; *bignum-precision*
128
&gt; (set! *bignum-precision* 256)
256
&gt; pi
3.141592653589793238462643383279502884197169399375105820974944592307816406286198E0
</pre>

<p>
<em class=def id="bignump">bignum?</em> returns #t if its argument is a big number of some type; I use "bignum" 
for any big number, not just integers.  To create a big number,
either include enough digits to overflow the default types, or use the <em class=def id="bignum">bignum</em> function.
Its argument is a string representing the desired number:
</p>

<pre class="indented">
&gt; (bignum "123456789123456789")
123456789123456789
&gt; (bignum "1.123123123123123123123123123")
1.12312312312312312312312312300000000009E0
</pre>


<blockquote> 
<div class="indented">

<p>In the non-gmp case, if s7 is built using doubles (s7_Double in s7.h), the float "epsilon" is
around (expt 2 -53), or about 1e-16.  In the gmp case, it is around (expt 2 (- *bignum-precision*)).
So in the default case (precision = 128), using gmp:
</p>

<pre class="indented">
&gt; (= 1.0 (+ 1.0 (expt 2.0 -128)))
#t
&gt; (= 1.0 (+ 1.0 (expt 2.0 -127)))
#f
</pre>

<p>and in the non-gmp case:
</p>

<pre class="indented">
&gt; (= 1.0 (+ 1.0 (expt 2 -53)))
#t
&gt; (= 1.0 (+ 1.0 (expt 2 -52)))
#f
</pre>

<p>In the gmp case, integers and ratios are limited only by the size of memory,
but reals are limited by *bignum-precision*.  This means, for example, that
</p>

<pre class="indented">
&gt; (floor 1e56) ; *bignum-precision* is 128
99999999999999999999999999999999999999927942405962072064
&gt; (set! *bignum-precision* 256)
256
&gt; (floor 1e56)
100000000000000000000000000000000000000000000000000000000
</pre>

<p>The non-gmp case is similar, but it's easy to find the edge cases:
</p>

<pre class="indented">
&gt; (floor (+ 0.9999999995 (expt 2.0 23)))
8388609
</pre>
</div> 
</blockquote>





<div class="header" id="math"><h4>math functions</h4></div>


<p>
s7 includes:
</p>

<ul>
<li>sinh, cosh, tanh, asinh, acosh, atanh
<li>logior, logxor, logand, lognot, logbit?, ash, integer-length, integer-decode-float
<li>random
<li>nan?, infinite?
</ul>

<p>
The random function can take any numeric argument, including 0.
The following constants are predefined: pi, most-positive-fixnum, most-negative-fixnum.
Other math-related differences between s7 and r5rs:
</p>

<ul>
<li>rational? and exact mean integer or ratio (i.e. not floating point), inexact means not exact.
<li>floor, ceiling, truncate, and round return (exact) integer results.
<li>"#" does not stand for an unknown digit.
<li>the "@" complex number notation is not supported ("@" is an exponent marker in s7).
<li>"+i" is not considered a number; include the real part.
<li>modulo, remainder, and quotient take integer, ratio, or real arguments.
<li>lcm and gcd can take integer or ratio arguments.
<li>log takes an optional second argument, the base.
<li>'.' and an exponent can occur in a number in any base.
<li>rationalize returns a ratio! 
<li>case is significant in numbers, as elsewhere: #b0 is 0, but #B0 is an error.
</ul>

<pre class="indented">
&gt; (exact? 1.0)
#f
&gt; (rational? 1.5)
#f
&gt; (floor 1.4)
1
&gt; (remainder 2.4 1)
0.4
&gt; (modulo 1.4 1.0)
0.4
&gt; (lcm 3/4 1/6)
3/2
&gt; (log 8 2)
3
&gt; (number-&gt;string 0.5 2)
"0.1"
&gt; (string-&gt;number "0.1" 2)
0.5
&gt; (rationalize 1.5)
3/2
&gt; (make-rectangular 1/2 0)
1/2
&gt; (logbit? 6 1) ; argument order, (logbit? int index), follows gmp, not CL
#t
</pre>

<blockquote>
<div class="indented">

<p>The exponent itself is always in base 10; this follows gmp usage.
Scheme normally uses "@" for its useless polar notation, but that
means <code>(string-&gt;number "1e1" 16)</code> is ambiguous &mdash; is the "e" a digit or an exponent marker?
In s7, "@" is an exponent marker.
</p>

<pre class="indented">
&gt; (string-&gt;number "1e9" 2)  ; (expt 2 9)
512.0
&gt; (string-&gt;number "1e1" 12) ; "e" is not a digit in base 12
#f
&gt; (string-&gt;number "1e1" 16) ; (+ (* 1 16 16) (* 14 16) 1)
481
&gt; (string-&gt;number "1.2e1" 3); (* 3 (+ 1 2/3))
5.0
</pre>
</div>


<div class="indented">

<p>Should s7 predefine the numbers +inf.0, -inf.0, and nan.0?  It doesn't currently, but you can
get them via log or 1/0 (see <a href="#r7rs">below</a>).
But what is <code>(/ 1.0 0.0)</code>?  s7 gives a "division by zero" error here, and also in <code>(/ 1 0)</code>.
Guile returns +inf.0 in the first case, which seems reasonable, but a "numerical overflow" error in the second.
Slightly weirder is <code>(expt 0.0 0+i)</code>.  Currently s7 returns 0.0, Guile returns +nan.0+nan.0i,
Clisp and sbcl throw an error.  Everybody agrees that <code>(expt 0 0)</code> is 1, and Guile thinks
that <code>(expt 0.0 0.0)</code> is 1.0.  But <code>(expt 0 0.0)</code> and <code>(expt 0.0 0)</code> return different
results in Guile (1 and 1.0), both are 0.0 in s7, the first is an error in Clisp, but the second returns 1,
and so on &mdash; what a mess!  This mess was made a lot worse than it needs to be when the IEEE decreed that
0.0 equals -0.0, so we can't tell them apart, but that they produce different results in nearly every use!  
</p>

<pre class="indented">
scheme@(guile-user)&gt; (= -0.0 0.0)
#t
scheme@(guile-user)&gt; (negative? -0.0)
#f
scheme@(guile-user)&gt; (= (/ 1.0 0.0) (/ 1.0 -0.0))
#f
scheme@(guile-user)&gt;  (&lt; (/ 1.0 -0.0) -1e100 1e100 (/ 1.0 0.0))
#t
</pre>

<p>
How can they be equal? In s7, the sign
of -0.0 is ignored, and they really are equal.
One other oddity: two floats can satisfy eq? and yet not be eqv?:
<code>(eq? nan.0 nan.0)</code> might be #t (it is unspecified), but <code>(eqv? nan.0 nan.0)</code> is #f.
The same problem afflicts memq and assq.  
</p>
</div>


<div class="indented">

<p>The <em class=def id="random">random</em> function takes a range and an optional state, and returns a number 
between zero and the range, of the same type as the range.  It is perfectly reasonable
to use a range of 0, in which case random returns 0.
<em class=def id="makerandomstate">make-random-state</em> creates a new random state from a seed.  If no state is passed,
random uses some default state initialized from the current time.  <em class=def id="randomstatep">random-state?</em> returns #t if passed a random state object.
</p>

<pre class="indented">
&gt; (random 0)
0
&gt; (random 1.0)
0.86331198514245
&gt; (random 3/4)
654/1129
&gt; (random 1+i)
0.86300308872748+0.83601002730848i
&gt; (random -1.0)
-0.037691127513267
&gt; (define r0 (make-random-state 1234))
r0
&gt; (random 100 r0)
94
&gt; (random 100 r0)
19
&gt; (define r1 (make-random-state 1234))
r1
&gt; (random 100 r1)
94
&gt; (random 100 r1)
19
</pre>

<p>copy the random-state to save a spot in a random number sequence, or save the random-state as a list via
random-state-&gt;list, then to restart from that point, apply make-random-state to that list.
</p>
</div>


<div class="indented">

<p>I can't find the right tone for this section; this is the 400-th revision; I wish I were a better writer!
</p>

<p>In some Schemes,
"rational" means "could possibly be
expressed equally well as a ratio: floats are approximations".  In s7 it's: "is actually expressed (at the scheme level) as a ratio (or an integer of course)";
otherwise "rational?" is the same as "real?":
</p>

<pre class="indented">
(not-s7)&gt; (rational? (sqrt 2))
#t
</pre>

<p>That 1.0 is represented at the IEEE-float level as a sort of
ratio does not mean it has to be a scheme ratio; the two notions are independent.
</p>

<p>But that confusion is trivial compared to the completely nutty "inexact integer".
As I understand it, "inexact" originally meant "floating point", and "exact" meant integer or ratio of integers.
But words have a life of their own.
0.0 somehow became an "inexact" integer (although it can be represented exactly in floating
point).  
+inf.0 must be an integer &mdash;
its fractional part is explicitly zero!  But +nan.0... 
And then there's:
</p>

<pre class="indented">
(not-s7)&gt; (integer? 9007199254740993.1)
#t
</pre>

<p>
When does this matter?  I often need to index into a vector, but the index is a float (a "real" in Scheme-speak: its
fractional part can be non-zero).
In one Scheme:
</p>

<pre class="indented">
(not-s7)&gt; (vector-ref #(0) (floor 0.1))
ERROR: Wrong type (expecting exact integer): 0.0   ; [why?  "it's probably a programmer mistake"!]
</pre>

<p>Not to worry, I'll use inexact-&gt;exact:
</p>

<pre class="indented">
(not-s7)&gt; (inexact-&gt;exact 0.1)
3602879701896397/36028797018963968                  ; [why? "floats are ratios"!]
</pre>

<p>So I end up using the verbose <code>(floor (inexact-&gt;exact ...))</code> everywhere, and even
then I have no guarantee that I'll get a legal vector index. 
</p>

<p>When I started work on s7, I thought perhaps
"exact" could mean "is represented exactly in the computer".  We'd have integers and ratios exact; 
reals and complex exact if they are exactly
represented in the current floating point implementation.  
0.0 and 0.5 might be exact if the printout isn't misleading, and 0.1 is inexact.
"integer?" and friends would refer instead to the programmer's point of view.
That is, if the programmer uses 1 or if the thing prints as 1, it is the integer 1, whereas 1.0
means floating point (not integer!). 
And to keep exactness in view, we'd have
to monitor which operations introduce inexactness &mdash; a kind of interval arithmetic.
But then what would inexact-&gt;exact do?  
</p>

<p>
I have never seen any use made of the exact/inexact distinction &mdash; just
wild flailing to try get around it.
I think the whole idea is confused and useless, and leads
to verbose and buggy code.  
If we discard it,
we can maintain backwards compatibility via:
</p>

<pre class="indented">
(define exact? rational?)
(define (inexact? x) (not (rational? x)))
(define inexact-&gt;exact rationalize) ; or floor
(define (exact-&gt;inexact x) (* x 1.0))
</pre>

<p>#i and #e are also useless because you can
have any number after, for example, #b:
</p>

<pre class="indented">
&gt; #b1.1
1.5
&gt; #b1e2
4.0
&gt; #o17.5+i
15.625+1i
</pre>

<p>Speaking of #b and friends, what should <code>(string-&gt;number "#xffff" 2)</code> return?
</p>
</div>



<div class="indented">

<pre>
(define (log-n-of n . ints)     ; return the bits on in exactly n of ints
  (let ((len (length ints)))
    (cond ((= len 0) (if (= n 0) -1 0))
	  ((= n 0)   (lognot (apply logior ints)))
	  ((= n len) (apply logand ints))
	  ((&gt; n len) 0)
	  (#t 
	   (do ((1s 0)
		(prev ints)
		(i 0 (+ i 1)))
	       ((= i len) 1s)
	     (let ((cur (ints i)))
	       (if (= i 0)
		   (set! 1s (logior 1s (logand cur (apply log-n-of (- n 1) (cdr ints)))))
		   (let* ((mid (cdr prev))
			  (nxt (if (= i (- len 1)) () (cdr mid))))
		     (set! (cdr prev) nxt)  
		     (set! 1s (logior 1s (logand cur (apply log-n-of (- n 1) ints))))
		     (set! (cdr prev) mid)
		     (set! prev mid)))))))))
</pre>

</div>

</blockquote>







<div class="header" id="define*"><h4>define*, lambda*</h4></div>


<p><em class=def id="definestar">define*</em> and
 <em class=def id="lambdastar">lambda*</em>
are extensions of define and lambda that make it easier
to deal with optional, keyword, and rest arguments.  
The syntax is very simple: every argument to define* has a default value
and is automatically available as a keyword argument.  The default value
is either #f if unspecified, or given in a list whose first member is
the argument name.
The last argument
can be preceded by :rest or a dot to indicate that all other trailing arguments
should be packaged as a list under that argument's name.  A trailing or rest
argument's default value is ().
You can use
:optional and :key, but they are ignored.  
</p>

<pre class="indented">
(<em class=red>define*</em> (hi a (b 32) (c "hi")) (list a b c))
</pre>

<p>Here the argument "a" defaults to #f, "b" to 32, etc.
When the function is called, 
the argument names are set from the values passed the function,
then any unset arguments are bound to their default values, evaluated in left-to-right order.
As the current argument list is scanned,  any name that occurs as a keyword, :arg for example where the parameter name is arg,
sets that argument's new value.  Otherwise, as values occur, they
are plugged into the actual argument list based on their position, counting a keyword/value pair as one argument.
This is called an optional-key list in CLM.  So, taking the function
above as an example:
</p>

<pre class="indented">
&gt; (hi 1) 
(1 32 "hi")
&gt; (hi :b 2 :a 3) 
(3 2 "hi")
&gt; (hi 3 2 1) 
(3 2 1)
</pre>

<p>See s7test.scm for many examples.
</p>


<blockquote>

<div class="indented">
<p>The combination of optional and keyword arguments is viewed with disfavor in the Lisp
community, but the problem is in CL's implementation of the idea, not the idea itself.
I've used the s7 style since around 1976, and have never found it confusing.  The mistake 
in CL is to require the optional arguments if a keyword argument occurs, and to consider them as distinct from the
keyword arguments.  So everyone forgets and puts a keyword where CL expects a required-optional
argument.  CL then does something ridiculous, and the programmer stomps around shouting about keywords, but the fault lies with CL.
If s7's way is considered too loose, one way to tighten it might be to insist that once a keyword
is used, only keyword argument pairs can follow.  
</p>
</div>


<div class="indented">
<p>A natural companion of lambda* is named let*.  In named let, the implicit function's
arguments have initial values, but thereafter, each call requires the full set of arguments.
Why not treat the initial values as default values? 
</p>

<pre class="indented">
&gt; (let* func ((i 1) (j 2)) 
    (+ i j (if (&gt; i 0) (func (- i 1)) 0)))
5
&gt; (letrec ((func (lambda* ((i 1) (j 2)) 
                   (+ i j (if (&gt; i 0) (func (- i 1)) 0)))))
    (func))
5
</pre>

<p>This is consistent with the lambda* arguments because their defaults are
already set in left-to-right order, and as each parameter is set to its default value,
the binding is added to the default value expression environment (just as if it were a let*).
</p>

<p>In CL, keyword default values are handled in the same way:
</p>

<pre class="indented">
&gt; (defun foo (&amp;key (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c)) 
FOO 
&gt; (foo :b 2 :a 60) 
(60 2 67) 
</pre>

<p>In s7, we'd use:
</p>

<pre class="indented">
(define* (foo (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c))
</pre>

</div>


<div class="indented">

<p>If you want a version of define* that insists
that any arguments before the keyword :optional are required:
</p>

<pre class="indented">
(define-macro (define** declarations . forms)
  (let ((name (car declarations))
	(args (cdr declarations)))
    (define (position thing lst count)
      (if (or (null? lst)
	      (not (pair? (cdr lst)))) ; for dotted arg = "rest" arg
	  #f
	  (if (eq? thing (car lst))
	      count
	      (position thing (cdr lst) (+ count 1)))))
    (let ((required-args (position :optional args 0)))
      (if required-args
	  `(define* (,name . func-args)
	     (if (&lt; (length func-args) ,required-args)
		 (error "~A requires ~D argument~A: ~A" 
			',name ,required-args 
                        (if (&gt; ,required-args 1) "s" "") 
                        func-args)
		 (apply (lambda* ,args ,@forms) func-args)))
	  `(define* ,declarations ,@forms)))))

&gt; (define** (hi a :optional (b 23)) (list a b))
hi
&gt; (hi 1)
(1 23)
&gt; (hi)
;hi requires 1 argument: ()
</pre>

</div>


<div class="indented">

<p>To try to catch what I believe are usually mistakes, I added two
error checks.  One is triggered if you set the same parameter twice
in the same call, and the other if an unknown keyword is encountered
in the key position.  These problems arise in a case such as
</p>

<pre class="indented">
(define* (f (a 1) (b 2)) (list a b))
</pre>

<p>You could do any of the following by accident:
</p>

<pre class="indented">
(f 1 :a 2)  ; what is a?
(f :b 1 2)  ; what is b?
(f :c 3)    ; did you really want a to be :c and b to be 3?
</pre>

<p>In the last case, to pass a keyword deliberately, either include the
argument keyword: <code>(f :a :c)</code>, or make the default value a keyword:
<code>(define* (f (a :c) ...))</code>.
To turn off this error check, add :allow-other-keys at the end of the parameter list.
</p>

</div>


<div class="indented">

<p>s7's lambda* arglist handling is not the same as CL's lambda-list.  First,
you can have more than one :rest parameter:
</p>

<pre class="indented">
&gt; ((lambda* (:rest a :rest b) (map + a b)) 1 2 3 4 5) 
'(3 5 7 9)
</pre>

<p>and second, the rest parameter, if any, takes up an argument slot just like any other
argument:
</p>

<pre class="indented">
&gt; ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 32)
(32 1 ())

&gt; ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 1 2 3 4 5)
(1 3 (2 3 4 5))
</pre>

<p>CL would agree with the first case if we used &amp;key for 'c', but would give an error in the second.
Of course, the major difference is that s7 keyword arguments don't insist that the key be present.
The :rest argument is needed in cases like these because we can't use an expression
such as:
</p>

<pre class="indented">
&gt; ((lambda* ((a 3) . b c) (list a b c)) 1 2 3 4 5)
stray dot?
</pre>

<p>Yet another nit: the :rest argument is not considered a keyword argument, so
</p>

<pre class="indented">
&gt; (define* (f :rest a) a)
f
&gt; (f :a 1)
(:a 1)
</pre>
</div>


</blockquote>






<div class="header" id="macros"><h4>macros</h4></div>


<p><em class=def id="definemacro">define-macro</em>, 
<em class=def id="definemacrostar">define-macro*</em>, 
defmacro, defmacro*, <em class=def id="macroexpand">macroexpand</em>, 
<em class=def id="gensym">gensym</em>, and 
<em class=def id="macrop">macro?</em>
implement the standard old-time macros.  
</p>

<pre class="indented">
&gt; (define-macro (<em class=def id="trace">trace</em> f)
    `(define ,f 
       (apply lambda 'args 
         `((format #t "(~A ~{~A~^ ~}) -&gt; " ',,f args)
           (let ((val (apply ,,f args))) 
             (format #t "~A~%" val) 
             val)))))
&gt; (trace abs)
abs
&gt; (abs -1.5)
(abs -1.5) -&gt; 1.5
1.5
</pre>

<p>macroexpand can help debug a macro.  I always forget that it
wants an expression:
</p>

<pre class="indented">
&gt; (define-macro (add-1 arg) `(+ 1 ,arg))
add-1
&gt; (macroexpand (add-1 32)) ; (macroexpand add-1) will complain about "car argument, add-1"
(+ 1 32)
</pre>

<p>gensym returns a symbol that is guaranteed to be unused.  It takes an optional string argument
giving the new symbol name's prefix.
</p>

<pre class="indented">
(define-macro (pop! sym)
  (let ((v (<em class=red>gensym</em>)))
    `(let ((,v (car ,sym)))
       (set! ,sym (cdr ,sym))
       ,v)))
</pre>

<p>As in define*, the starred forms give optional and keyword arguments:
</p>

<pre class="indented">
&gt; (define-macro* (add-2 a (b 2)) `(+ ,a ,b))
add-2
&gt; (add-2 1 3)
4
&gt; (add-2 1)
3
&gt; (add-2 :b 3 :a 1)
4
</pre>

<p>A bacro is a macro that expands its body and evaluates
the result in the calling environment.
</p>

<pre class="indented">
(define setf
  (let ((args (gensym)))
    (apply <em class=red>define-bacro</em>
	   `((setf-1 . ,args)        
	     (if (not (null? ,args))
		 (begin
		   (apply set! (car ,args) (cadr ,args) ())
		   (apply setf (cddr ,args))))))
    setf-1))
</pre>


<p>
Here define-bacro makes it possible
to implement setf without any run-time consing or extra work &mdash; the second evaluation
just sees #&lt;unspecified&gt; &mdash; so this is as fast as a function call.
The setf argument is a gensym (created when setf is defined) so that its name does not shadow any existing
variable.  Bacros expand in the calling environment, and a normal argument name
might shadow something in that environment while the bacro is begin expanded.
</p>
<p>
See s7test.scm for many examples including such perennial favorites as
when, loop, dotimes, do*, enum, pushnew, and defstruct.
</p>



<blockquote>

<div class="indented">

<p>As the setf example shows, a macro is a first-class citizen of s7.  You can
pass it as a function argument, apply it to a list, return it from a function,
call it recursively, 
and assign it to a variable.  You can even set its procedure-setter!
</p>

<pre class="indented">
&gt; (define-macro (hi a) `(+ ,a 1))
hi
&gt; (apply hi '(4))
5
&gt; (define (fmac mac) (apply mac '(4)))
fmac
&gt; (fmac hi)
5
&gt; (define (fmac mac) (mac 4))
fmac
&gt; (fmac hi)
5
&gt; (define (make-mac)
    (define-macro (hi a) `(+ ,a 1))
    hi)
make-mac
&gt; (let ((x (make-mac)))
    (x 2))
3
&gt; (define-macro (ref v i) `(vector-ref ,v ,i))
ref
&gt; (define-macro (set v i x) `(vector-set! ,v ,i ,x))
set
&gt; (set! (procedure-setter ref) set)
#&lt;macro&gt;
&gt; (let ((v (vector 1 2 3))) (set! (ref v 0) 32) v)
#(32 2 3)
</pre>
</div>


<div class="indented">

<p>Backquote (quasiquote) in s7 is almost trivial.  Constants are unchanged, symbols are quoted,
",arg" becomes "arg", and ",@arg" becomes "(apply values arg)" &mdash; hooray for real multiple values!
It's almost as easy to write the actual macro body as the backquoted version of it. 
</p>

<pre class="indented">
&gt; (define-macro (hi a) `(+ 1 ,a))
hi
&gt; (procedure-source hi)
(lambda ({defmac}-16) (apply (lambda (a) <em class=red>({list} '+ 1 a))</em> (cdr {defmac}-16)))

;; so (define-macro (hi a) ({list} + 1 a)) is the same

&gt; (define-macro (hi a) `(+ 1 ,@a))
hi
&gt; (procedure-source hi)
(lambda ({defmac}-17) (apply (lambda (a) <em class=red>({list} '+ 1 ({apply_values} a)))</em> (cdr {defmac}-17)))

;; same: (define-macro (hi a) ({list} + 1 ({apply_values} a)))

&gt; (define-macro (hi a) ``(+ 1 ,,a))
hi
&gt; (procedure-source hi)
(lambda ({defmac}-18) (apply (lambda (a) <em class=red>({list} '{list} ({list} 'quote '+) 1 a))</em> (cdr {defmac}-18)))
</pre>

<p>and so on.  "{list}" is a special version of "list" to avoid name collisions
and handle a few tricky details (similarly for "{apply_values}").  There is no unquote-splicing
macro in s7;  ",@(...)" becomes "(unquote ({apply_values} ...))" at read-time.  There shouldn't be any unquote
either.  In Scheme the reader turns ,x into (unquote x), so:
</p>

<pre>
&gt; (let (,'a) unquote)
a
&gt; (let (, (lambda (x) (+ x 1))) ,,,,'3)
7
</pre>
<p>comma becomes a sort of symbol macro! I think I'll remove unquote; ,x and ,@x will still work
as expected, but there will not be any "unquote" or "unquote-splicing" in the resultant source code.  Just to make life difficult:
</p>
<pre>
&gt; (let (' 1) quote)
1
</pre>
<p>but that translation is so ingrained in lisp (it even works in Clisp) 
that I'm reluctant to change it.  The two unquote names, on the
other hand, seem unnecessary.
</p>
</div>



<div class="indented">
<p>macro? returns #t if its argument is a macro or a symbol whose value is a macro.
We can use it, and other macro-related stuff to make a version of macroexpand-all:
</p>

<pre class="indented">
(define-macro (fully-expand form)
  (define (expand form)
    (if (pair? form)
	(if (<em class=red>macro?</em> (car form))
	    (expand ((eval (procedure-source (car form))) form))
	    (cons (expand (car form))
		  (expand (cdr form))))
	form))
  (expand form))

&gt; (define-macro (hi a) `(+ 1 ,a))
hi
&gt; (define-macro (ha c) `(hi (+ ,c 1)))
ha
&gt; (fully-expand (define (ho b) (+ 1 (ha b))))
ho
&gt; (procedure-source ho)
(lambda (b) (+ 1 (+ 1 (+ b 1))))
</pre>

<p>fully-expand expands each macro it encounters by using the
procedure-source of that macro, that is, the function that the macro definition
expanded into:
</p>

<pre class="indented">
(define-macro (hi a) `(+ ,a 1))

&gt; (procedure-source hi)
(lambda ({defmac}-18) (apply (lambda (a) ({list} '+ a 1)) (cdr {defmac}-18)))
</pre>
</div>



<div class="indented">

<p>s7 macros are not hygienic.  For example,
</p>

<pre class="indented">
&gt; (define-macro (mac b) 
    `(let ((a 12)) 
       (+ a ,b)))
mac
&gt; (let ((a 1) (+ *)) (mac a))
144
</pre>

<p>This returns 144 because '+' has turned into '*', and 'a' is the internal 'a',
not the argument 'a'.  We get <code>(* 12 12)</code> where we might have expected
<code>(+ 12 1)</code>.  
Starting with the '+' problem, 
as long as the redefinition of '+' is local (that is, it happens after the macro definition), we can unquote the +:
</p>

<pre class="indented">
&gt; (define-macro (mac b) 
    `(let ((a 12)) 
       (,+ a ,b))) ; ,+ picks up the definition-time +
mac
&gt; (let ((a 1) (+ *)) (mac a))
24                 ; (+ a a) where a is 12
</pre>

<p>But the unquote trick won't work if we have previously loaded some file that redefined '+'
at the top-level (so at macro definition time, + is *, but we want the built-in +).
Although this example is silly, the problem is real in Scheme
because Scheme has no reserved words and only one name space.
</p>

<pre class="indented">
&gt; (define + *)
+
&gt; (define (add a b) (+ a b))
add
&gt; (add 2 3)
6
&gt; (define (divide a b) (/ a b))
divide
&gt; (divide 2 3)
2/3
&gt; (set! / -) ; a bad idea &mdash; this turns off s7's optimizer
-
&gt; (divide 2 3)
-1
</pre>

<p>Obviously macros are not the problem here.  Since 
we might be loading
code written by others, it's sometimes hard to tell what names
that code depends on or redefines.
We need a way to get the pristine (start-up, built-in) value of '+'.
One long-winded way in s7 uses <a href="#initialenvironment">initial-environment</a>:
</p>

<pre class="indented">
&gt; (define + *)
+
&gt; (define (add a b) (with-environment (initial-environment) (+ a b)))
add
&gt; (add 2 3)
5
</pre>

<p>But this is hard to read, and it's not inconceivable that we might want all three
values of a symbol, the start-up value, the definition-time value, and the
current value.  The latter can be accessed with the bare symbol, the definition-time
value with unquote (','), and the start-up value with either initial-environment
or #_&lt;name&gt;.  That is, #_+ is a reader macro for <code>(with-environment (initial-environment) +)</code>.
</p>

<pre class="indented">
&gt; (define-macro (mac b) 
    `(<em class=red>#_let</em> ((a 12)) 
       (<em class=red>#_+</em> a ,b))) ; #_+ and #_let are start-up values
mac
&gt; (let ((a 1) (+ *)) (mac a))
24                 ; (+ a a) where a is 12 and + is the start-up +

;;; make + generic (there's a similar C-based example below)
&gt; (define (+ . args) 
    (if (null? args) 0 
        (apply (if (number? (car args)) <em class=red>#_+ #_string-append</em>) args)))
+
&gt; (+ 1 2)
3
&gt; (+ "hi" "ho")
"hiho"
</pre>

<p>#_&lt;name&gt; could be implemented via *#readers*:
</p>

<pre class="indented">
(set! *#readers*
  (cons (cons #\_ (lambda (str)
		    (with-environment 
                      (initial-environment) 
                      (string-&gt;symbol (substring str 1)))))
	*#readers*))
</pre>

<br>
<p>
So, now we have only the variable capture problem ('a' has been captured in the preceding examples).
This is the only thing that the gigantic "hygienic macro" systems actually deal with:
a microscopic problem that you'd think, from the hype, was up there with malaria and the
national debt.  gensym is the standard approach:
</p>

<pre class="indented">
&gt; (define-macro (mac b) 
    (let ((var (<em class=red>gensym</em>))) 
      `(#_let ((,var 12))
         (#_+ ,var ,b))))
mac
&gt; (let ((a 1) (+ *)) (mac a))
13

;; or use lambda:
&gt; (define-macro (mac b) 
  `((lambda (b) (let ((a 12)) (#_+ a b))) ,b))
mac
&gt; (let ((a 1) (+ *)) (mac a))
13
</pre>

<p>If gensym worries you because it's creating a symbol on each macro invocation,
use a closure as in the bacro example above.
gensym can make the macro code
unreadable in more complex cases.  It is possible to
write a macro to do the gensymification for us, but in s7 it is easier to
use the environment functions.
The procedure-environment of a macro is the environment at its definition time, just like a function.
By wrapping the macro body in with-environment, we make sure anything in that body reflects 
the definition environment, not the calling environment.  We then augment that environment
with the macro arguments getting their values from the call-time environment:
</p>

<pre class="indented">
(define-macro (define-immaculo name-and-args . body)
  (let* ((gensyms (map (lambda (g) (gensym)) (cdr name-and-args)))
	 (args (cdr (copy name-and-args)))
	 (name (car name-and-args))
	 (set-args (map (lambda (a g) `(list ',g ,a)) args gensyms))
	 (get-args (map (lambda (a g) `(quote (cons ',a ,g))) args gensyms))
	 (blocked-args (map (lambda (a) `(,a ',a)) args))     
	 (new-body (list (apply let blocked-args body))))    ; unquote args
    `(define-macro ,name-and-args
       `(let ,(list ,@set-args)
          ,(list 'with-environment 
                 (append (list 'augment-environment) 
                         (list (list 'procedure-environment ,name)) 
                         (list ,@get-args))
                 ',@new-body)))))

&gt; (define-immaculo (mac c d) `(let ((a 12) (b 3)) (+ a b ,c ,d)))
mac
&gt; (let ((a 21) (b 10) (+ *)) (mac a b))
46     ; (+ 12 3 21 10) with the definition-time value of +
&gt; (let ((a 21) (b 10) (+ *)) (mac a (+ b 10)))
136    ; (+ 12 3 21 (* 10 10)), (+ b 10) is treated as (* b 10)
       ;   because (+ b 10) refers to the '+' and 'b' in the calling environment
</pre>

<p>Here's a simpler version that does not try to import the definition environment.
Better would be to use a gensym rather than "e" for the current-environment.
</p>
<pre>
(define-macro (define-immaculo name-and-args . body)
  (let ((new-args (map (lambda (arg) 
                         `(list (quote ,arg) ,arg)) 
                       (cdr name-and-args)))
	(wrapped-args (map (lambda (arg) 
                             `(,arg (quote (with-environment e ,arg)))) 
                           (cdr name-and-args))))
    (let ((new-body (apply let wrapped-args body)))
      `(define-macro ,name-and-args
	 `(let ,(list ,@new-args)
	    (let ((e (current-environment)))
	      ,',new-body))))))

&gt; (define-immaculo (mac b) 
    `(let ((a 1)) (+ a ,b)))
mac
&gt; (let ((a 32)) (mac a))
33
&gt; (procedure-source mac) ; I've edited the results to try to make the transformation clearer
(define-macro (mac b)
  `(let ((b ,b))
     (let ((e (current-environment)))	      
       (let ((a 1))     ; here is the original macro body
         (+ a (with-environment e b))))))
</pre>

<p>Apply let is very similar to eval:
</p>
<pre>
&gt; (apply let '((a 2) (b 3)) '((+ a b)))
5
&gt; (eval '(+ a b) (environment '(a . 2) '(b . 3)))
5
&gt; ((apply lambda '(a b) '((+ a b))) 2 3)
5
</pre>
<p>But we're using it here as a kind of "replace":
</p>
<pre>
&gt; (apply let '((a 2) (b 3)) '((list + a b))) ; a -&gt; 2, b -&gt; 3
(+ 2 3)
</pre>
<p>The redundant-looking double lists are for apply's benefit.  We could
use a trailing null instead (mimicking apply* in some ancient lisps):
</p>
<pre>
&gt; (apply let '((a 2) (b 3)) '(list + a b) ())
(+ 2 3)
</pre>

<br><br>

<p>But why insist on writing macros the old way?
We can use
with-environment from the start, writing an immaculo directly:
</p>
<pre>
(define-macro (mac b)
  `(with-environment
       (environment (cons 'b ,b)) 
     (let ((a 12))
       (+ a b))))

&gt; (let ((a 1) (+ *)) (mac a))
13
</pre>

<p>If the syntax strikes you as baroque, perhaps:
</p>
<pre>
(define-macro (glet bindings . body)
  `(with-environment
       (environment 
	 ,@(map (lambda (b) 
                  `(cons ',(car b) ,(cadr b))) 
                bindings))
     ,@body))

(define-macro (mac b)
  `(glet ((b ,b))
     (let ((a 12))
       (+ a b))))
</pre>

<p>If you want the macro's expanded result
to be evaluated in its definition environment:
</p>
<pre>
(let ((a 3))
  (define-macro (mac b)
    `(with-environment 
	 (environment (cons 'b ,b)
		      (procedure-environment mac))
       (+ a b)))       ; definition-time "a", call-time "b"
  (define-macro (mac-1 b)
    `(+ a ,b))         ; call-time "a" and "b"
  (let ((a 32))
    (list (mac 1) 
	  (mac-1 1))))
</pre>

<p>Here's define-immaculo in the new form:
</p>

<pre>
(define-macro (define-safe-macro name&amp;args . body)
  `(define-macro ,name&amp;args
     (with-environment 
         (#_environment 
	  (initial-environment)
	  ,@(#_let ((rest (#_if (#_list? name&amp;args) 
			    #f 
			    (#_list-tail name&amp;args (#_abs (#_length name&amp;args))))))
	    (#_append 
	     (#_map (#_lambda (b) 
		    `(#_cons ',b ,b))
		  (#_cdr name&amp;args))
	     (#_if rest `((#_cons ',rest ,rest)) ()))))
	,@body)))
</pre>
</div>


<!--
(define-macro (begin-1 . body)
  `(with-environment 
       (current-environment) 
     ,@body))

(define-macro (let-1 bindings . body)
  `(with-environment 
       (environment 
	(current-environment) 
	,@(map (lambda (b) 
		 `(cons ',(car b) ,(cadr b))) 
	       bindings)) 
     ,@body))

(define-macro (let*-1 bindings . body)
  `(with-environment
       (environment 
	(current-environment))
     ,@(map (lambda (b)
	      `(define ,(car b) ,(cadr b)))
	    bindings)
     ,@body))

(define-macro (letrec*-1 bindings . body)
  `(with-environment
       (environment 
	(current-environment)
	,@(map (lambda (b) 
		 `(cons ',(car b) #<undefined>))
	       bindings)) 
     ,@(map (lambda (b)
	      `(set! ,(car b) ,(cadr b)))
	    bindings)
     ,@body))

(define-macro (safe-let bindings . body)
  `(with-environment 
       (#_environment 
	(initial-environment)
	,@(#_map (#_lambda (b) 
		 `(#_cons ',(#_car b) ,(#_cadr b)))
	       bindings))
     ,@body))
-->



<div class="indented">

<p>There is another problem with macros: accidental loops.  Take the following
example; we're trying to write a macro that defines a function
that returns its argument in a list statement.
</p>

<pre class="indented">
&gt; (define-macro (hang arg) `(define ,arg `(list (cdr ,,arg)))) ; obvious, no?
hang
&gt; (macroexpand (hang (f a)))
(define #1=(f a) ({list} 'list ({list} 'cdr #1#)))
&gt; (hang (f a))
f
&gt; (procedure-source f)
(lambda #1=(a) ({list} 'list ({list} 'cdr (f . #1#))))
&gt;(f 1)
</pre>

<p>And now we are hung &mdash; we've created a procedure with an
infinite loop!  This is surprisingly easy to do by accident.
Here's one way out:
</p>

<pre class="indented">
&gt; (define-macro (hang arg) `(define ,arg `(list ,,@(cdr arg))))
hang
&gt; (macroexpand (hang (f a)))
(define (f a) ({list} 'list a))
&gt; (hang (f a))
f
&gt; (f 1)
(list 1)
</pre>
</div>


<div class="indented">

<p>But we should end on a happy note.  Here is Peter Seibel's wonderful once-only macro:
</p>

<pre class="indented">
(define-macro (once-only names . body)
  (let ((gensyms (map (lambda (n) (gensym)) names)))
    `(let (,@(map (lambda (g) (list g '(gensym))) gensyms))
       `(let (,,@(map (lambda (g n) (list list g n)) gensyms names))
          ,(let (,@(map (lambda (n g) (list n g)) names gensyms))
             ,@body)))))
</pre>

<!-- this was:
(define-macro (once-only names . body)
  (let ((gensyms (map (lambda (n) (gensym)) names)))
    `(let (,@(map (lambda (g) `(,g (gensym))) gensyms))
       `(let (,,@(map (lambda (g n) ``(,,g ,,n)) gensyms names))
          ,(let (,@(map (lambda (n g) `(,n ,g)) names gensyms))
             ,@body)))))
-->

<p>From the land of sparkling bacros:
</p>

<pre class="indented">
(define once-only
  (let ((names (gensym))
	(body (gensym)))
    (symbol-&gt;value (apply define-bacro `((,(gensym) ,names . ,body)
      `(let (,@(map (lambda (name) `(,name ,(eval name))) ,names))
	 ,@,body))))))
</pre>
</div>

</blockquote>




<div class="header" id="pws"><h4>procedure-setter</h4></div>

<pre class="indented">
(<em class=def>procedure-setter</em> proc)
(<em class=def id="procedurewithsetter">make-procedure-with-setter</em> proc setter)
</pre>

<p>Each function (or macro!) can have an associated setter, much like defsetf in CL.  As a convenience, there's also
a way to associate the two functions under one name: make-procedure-with-setter.
The setter is called when the procedure is the target of set!  Its last argument is the
value passed to set!:
</p>

<pre class="indented">
&gt; (procedure-setter cadr)
#f
&gt; (set! (procedure-setter cadr) 
        (lambda (lst val) 
          (set! (car (cdr lst)) val)))
#&lt;lambda (lst val)&gt;
&gt; (procedure-source (procedure-setter cadr))
(lambda (lst val) (set! (car (cdr lst)) val))
&gt; (let ((lst (list 1 2 3))) 
    (set! (cadr lst) 4) 
    lst)
(1 4 3)
</pre>

<p>In some cases, the setter needs to be a macro:
</p>
<pre class="indented">
&gt; (set! (procedure-setter logbit?)
        (symbol-&gt;value 
          (define-macro (m var index on) ; here we want to set "var", so we need a macro
	    `(if ,on
	         (set! ,var (logior ,var (ash 1 ,index)))
	         (set! ,var (logand ,var (lognot (ash 1 ,index))))))))
#&lt;macro&gt;
&gt; (define (mingle a b)
    (let ((r 0))
      (do ((i 0 (+ i 1)))
          ((= i 31) r)
        (set! (logbit? r (* 2 i)) (logbit? a i))
        (set! (logbit? r (+ (* 2 i) 1)) (logbit? b i)))))
mingle
&gt; (mingle 6 3) ; the INTERCAL mingle operator?
30
</pre>

<blockquote>


<div class="indented">

<p>Here is a pretty example of make-procedure-with-setter:
</p>

<pre class="indented">
(define-macro (c?r path)
  ;; "path" is a list and "X" marks the spot in it that we are trying to access
  ;; (a (b ((c X)))) &mdash; anything after the X is ignored, other symbols are just placeholders
  ;; c?r returns a procedure-with-setter that gets/sets X

  (define (X-marks-the-spot accessor tree)
    (if (pair? tree)
	(or (X-marks-the-spot (cons 'car accessor) (car tree))
	    (X-marks-the-spot (cons 'cdr accessor) (cdr tree)))
	(if (eq? tree 'X) accessor #f)))

  (let ((body 'lst))
    (for-each
     (lambda (f)
       (set! body (list f body)))
     (reverse (X-marks-the-spot () path)))

    `(<em class=red>make-procedure-with-setter</em>
      (lambda (lst) 
	,body)
      (lambda (lst val)
	(set! ,body val)))))

&gt; ((c?r (a b (X))) '(1 2 (3 4) 5))
3

&gt; (let ((lst (list 1 2 (list 3 4) 5))) 
   (set! ((c?r (a b (X))) lst) 32)
   lst)
(1 2 (32 4) 5)

&gt; (procedure-source (c?r (a b (X))))
(lambda (lst) (car (car (cdr (cdr lst)))))

&gt; ((c?r (a b . X)) '(1 2 (3 4) 5))
((3 4) 5)

&gt; (let ((lst (list 1 2 (list 3 4) 5))) 
   (set! ((c?r (a b . X)) lst) '(32))
   lst)
(1 2 32)

&gt; (procedure-source (c?r (a b . X)))
(lambda (lst) (cdr (cdr lst)))

&gt; ((c?r (((((a (b (c (d (e X)))))))))) '(((((1 (2 (3 (4 (5 6)))))))))) 
6

&gt; (let ((lst '(((((1 (2 (3 (4 (5 6))))))))))) 
    (set! ((c?r (((((a (b (c (d (e X)))))))))) lst) 32) 
    lst)
(((((1 (2 (3 (4 (5 32)))))))))

&gt; (procedure-source (c?r (((((a (b (c (d (e X)))))))))))
(lambda (lst) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (car (car (car lst)))))))))))))))
</pre>	

<p>We can extend c?r into something incredibly useful!  A goto implementation using circular lists:
</p>

<pre class="indented">
(define-macro (define-with-goto name-and-args . body)
  ;; run through the body collecting label accessors, (label name)
  ;; run through getting goto positions, (goto name)
  ;; tie all the goto's to their respective labels (via set-cdr! essentially)
  
  (define (find-accessor type)
    (let ((labels ()))
      (define (gather-labels accessor tree)
	(if (pair? tree)
	    (if (equal? (car tree) type)
		(begin
		  (set! labels (cons (cons (cadr tree) 
					   (let ((body 'lst))
					     (for-each
					      (lambda (f)
						(set! body (list f body)))
					      (reverse (cdr accessor)))
					     (make-procedure-with-setter
					      (apply lambda '(lst) (list body))
					      (apply lambda '(lst val) `((set! ,body val))))))
				     labels))
		  (gather-labels (cons 'cdr accessor) (cdr tree)))
		(begin
		  (gather-labels (cons 'car accessor) (car tree))
		  (gather-labels (cons 'cdr accessor) (cdr tree))))))
      (gather-labels () body)
      labels))
	
  (let ((labels (find-accessor 'label))
	(gotos (find-accessor 'goto)))
    (if (not (null? gotos))
	(for-each
	 (lambda (goto)
	   (let* ((name (car goto))
		  (goto-accessor (cdr goto))
		  (label (assoc name labels))
		  (label-accessor (and label (cdr label))))
	     (if label-accessor
		 (set! (goto-accessor body) (label-accessor body))
		 (error 'bad-goto "can't find label: ~S" name))))
	   gotos))

    `(define ,name-and-args
       (let ((label (lambda (name) #f))
	     (goto (lambda (name) #f)))
	 ,@body))))

(define-with-goto (hi)
  (display "start ")
  (<em class=red>goto</em> 'the-end)
  (display "oops")
  (<em class=red>label</em> 'the-end)
  (display "all done"))
</pre>
</div>


<div class="indented">

<p>I wonder if it would be more consistent to use the
name "procedure/setter" in place of Guile's "make-procedure-with-setter".
Its syntax is closer to
vector than make-vector, for example.  
Even better: "dilambda":
</p>

<pre class="indented">
(define-macro (dilambda getter setter)
  `(make-procedure-with-setter
     (lambda ,@getter)
     (lambda ,@setter)))

(let ((a 32)) 
  (dilambda (() a) 
            ((b) (set! a b))))
</pre>

<p>"bilambda" would mix Latin and Greek since the Romans used "el", not "lambda", according to Wikipedia.
</p>
</div>

</blockquote>





<div class="header" id="generalizedset"><h4>applicable objects, generalized set!, generic functions</h4></div>


<p>A procedure with a setter can be viewed as one generalization of set!.  Another
treats objects as having predefined get and set functions.  In s7
lists, strings, vectors, hash-tables, environments, and any cooperating C or Scheme-defined objects
are both applicable and settable.  newLisp calls this implicit indexing, Gauche implements it
via object-apply, Guile via procedure-with-setter; CL's funcallable instance might be the same idea.
</p>

<p>
In <code>(vector-ref #(1 2) 0)</code>, for example, vector-ref is just a type
declaration.  But in Scheme, type declarations are unnecessary, so we get exactly
the same result from <code>(#(1 2) 0)</code>.  Similarly, <code>(lst 1)</code> is the
same as <code>(list-ref lst 1)</code>, and <code>(set! (lst 1) 2)</code> is the same
as <code>(list-set! lst 1 2)</code>.
I like this syntax:  the less noise, the better!
</p>

<blockquote>

<div class="indented">

<p>Well, maybe applicable strings look weird: <code>("hi" 1)</code> is #\i, but worse,
so is <code>(cond (1 =&gt; "hi"))</code>!  Even though a string, list, or vector is "applicable", it is
not currently considered to be a procedure, so <code>(procedure? "hi")</code> is #f.  map and for-each, however,
accept anything that apply can handle, so
<code>(map #(0 1) '(1 0))</code> is '(1 0).  (On the first call to map in this case, you get the result of
<code>(#(0 1) 1)</code> and so on).
string-&gt;list and vector-&gt;list are <code>(map values object)</code>.
Their inverses are (and always have been) equally trivial.
</p>


<p>The applicable object syntax makes it easy to write generic functions.
For example, s7test.scm has implementations of Common Lisp's sequence functions.
length, copy, reverse, fill!, map and for-each are generic in this sense (map always returns a list).
</p>

<pre class="indented">
&gt; (map (lambda (a b) (- a b)) (list 1 2) (vector 3 4))
(5 -3 9)
&gt; (length "hi")
2
</pre>

<p>Here is a function that returns an iterator.  It works for anything that
accepts an integer argument (e.g. list, string, vector, ...):
</p>

<pre class="indented">
(define (make-iterator obj)
  (let ((ctr 0))
    (lambda ()
      (and (&lt; ctr <em class=red>(length obj)</em>)
	   (let ((val <em class=red>(obj ctr)</em>))
	     (set! ctr (+ ctr 1))
	     val)))))
</pre>

<p>
Here's a generic FFT:
</p>

<pre class="indented">
(define* (cfft! data n (dir 1)) ; (complex data)
  (if (not n) (set! n (length data)))
  (do ((i 0 (+ i 1))
       (j 0))
      ((= i n))
    (if (&gt; j i)
	(let ((temp (data j)))
	  (set! (data j) (data i))
	  (set! (data i) temp)))
    (let ((m (/ n 2)))
      (do () 
	  ((or (&lt; m 2) (&lt; j m)))
	(set! j (- j m))
	(set! m (/ m 2)))
      (set! j (+ j m))))
  (let ((ipow (floor (log n 2)))
	(prev 1))
    (do ((lg 0 (+ lg 1))
	 (mmax 2 (* mmax 2))
	 (pow (/ n 2) (/ pow 2))
	 (theta (make-rectangular 0.0 (* pi dir)) (* theta 0.5)))
	((= lg ipow))
      (let ((wpc (exp theta))
	    (wc 1.0))
	(do ((ii 0 (+ ii 1)))
	    ((= ii prev))
	  (do ((jj 0 (+ jj 1))
	       (i ii (+ i mmax))
	       (j (+ ii prev) (+ j mmax)))
	      ((&gt;= jj pow))
	    (let ((tc (* wc (data j))))
	      (set! (data j) (- (data i) tc))
	      (set! (data i) (+ (data i) tc))))
	  (set! wc (* wc wpc)))
	(set! prev mmax))))
  data)

&gt; (cfft! (list 0.0 1+i 0.0 0.0))
(1+1i -1+1i -1-1i 1-1i)
&gt; (cfft! (vector 0.0 1+i 0.0 0.0))
#(1+1i -1+1i -1-1i 1-1i)
</pre>

<p>And a generic function that copies one sequence's elements into another sequence:
</p>
<pre class="indented">
(define (copy-into source dest) ; this is equivalent to (copy source dest)
  (do ((i 0 (+ i 1))) 
      ((= i (min (length source) (length dest))) 
       dest)
    (set! (dest i) (source i))))
</pre>

<p>but that is already built-in as the two-argument version of the copy function.
</p>
</div>


<div class="indented">

<p>There is one place where list-set! and friends are not the same as set!: the former
evaluate their first argument, but set! does not (with a quibble; see below):
</p>

<pre class="indented">
&gt; (let ((str "hi")) (string-set! (let () str) 1 #\a) str)
"ha"

&gt; (let ((str "hi")) (set! (let () str) 1 #\a) str)
;((let () str) 1 #\a): too many arguments to set!

&gt; (let ((str "hi")) (set! ((let () str) 1) #\a) str)
"ha"

&gt; (let ((str "hi")) (set! (str 1) #\a) str)
"ha"
</pre>

<p>set! looks at its first argument to decide what to set.
If it's a symbol, no problem.  If it's a list, set! looks at its car to see if it is
some object that has a setter.  If the car is itself a list, set! evaluates the internal
expression, and tries again.  So the second case above is the only one that won't work.
And of course:
</p>

<pre class="indented">
&gt; (let ((x (list 1 2))) 
    (set! ((((lambda () (list x))) 0) 0) 3) 
    x) 
(3 2)
</pre>
</div>


<div class="indented">

<p>By my count, around 20 of the Scheme built-in functions are already generic in the sense
that they accept arguments of many types (leaving aside the numeric and type checking functions, take for example equal?, display,
member, assoc, apply, eval, quasiquote, and values).  s7 extends that list with map, for-each, reverse,
and length, and adds a few others such as copy, fill!, sort!, object-&gt;string, and continuation?.
newLisp takes a more radical approach than s7: it extends operators such as '&gt;' 
to compare strings and lists, as well as numbers.  In map and for-each, however, you can mix the argument
types, so I'm not as attracted to making '&gt;' generic; you can't, for example, <code>(&gt; "hi" 32.1)</code>,
or even <code>(&gt; 1 0+i)</code>.
</p>
</div>


<div class="indented">
<p>The make-iterator function above raises an interesting issue.  What should the copy function
do if passed a closure?  To be consistent with copy as applied
to a hash-table-iterator, we want a snapshot of the current
state of the iteration:
</p>

<pre class="indented">
(define (iterator-&gt;string iterator)
  (let ((look-ahead (<em class="red">copy</em> iterator)))
    (string-append "#&lt;iterator ... " 
		   (object-&gt;string (look-ahead)) " "
		   (object-&gt;string (look-ahead)) " "
		   (object-&gt;string (look-ahead))
		   " ...&gt;")))

(let ((v (vector 0 1 2 3 4 5 6 7 8 9)))
  (let ((iterator (<em class=red>make-iterator</em> v)))
    (let* ((vals (list (iterator) (iterator) (iterator)))
           (description (iterator-&gt;string iterator))
           (more-vals (list (iterator) (iterator))))
      (list vals description more-vals))))
</pre>

<p>
which returns <code>'((0 1 2) "#&lt;iterator ... 3 4 5 ...&gt;" (3 4))</code>
But this consistency requires that we
copy the function's environment chain (all its non-global "closed over" state),
and each value in that chain:
</p>

<pre class="indented">
(define (make-iterator-with-filter obj func)
  (let ((iterator (make-iterator obj)))
    (letrec ((filter (lambda ()
		       (or (func (iterator))
			   (filter)))))
      filter)))

(let ((v (vector 0 1 2 3 4 5 6 7 8 9)))
  (let ((iterator (make-iterator-with-filter v 
		    (lambda (val)
		      (if (number? val)
			  (and (even? val)
			       val)
			  :all-done)))))
    ...))
</pre>

<p>			  
Now if we <code>(copy iterator)</code> in the let body above, but don't copy the internal iterator in the copy function,
the two iterators step on each other because they share the same 'ctr' variable.
If the copy function copies any closure it finds in the environment (so that the inner iterator is copied), we get an infinite loop
because 'filter' is in its own closure (thanks to letrec).
And if it copies all values in the environment, it copies the vector 
that is deliberately shared!  Our motto is "hack now, think later", so we try to add
circle checks and copy only closure environments, but now we have a big pile of
queasy code that assumes we have thought of everything.  Not likely.  And copy has
become incredibly wasteful; we might end up copying hundreds of local variables,
when all we actually want is access to the 'ctr' and 'obj' variables in the
current iterator's environment.  I'm getting ahead of the story, but suffice it
to say that <a href="#environments">environments</a> are first class citizens of s7.
We can think of the make-iterator function as defining an implicit class that contains
the slots 'ctr' and 'obj', and that returns an instance of that class.
So...
</p>

<pre class="indented">
(define-macro (with-iterator obj . body) 
  `(with-environment (procedure-environment ,obj) ,@body))

;; just for fun:
(define (reset-iterator iter)
  (with-iterator iter (set! ctr 0)))	

(define (iterator-obj iter)
  (with-iterator iter obj))

(define iterator-ctr 
  (make-procedure-with-setter 
   (lambda (iter)
     (with-iterator iter ctr))
   (lambda (iter new-ctr)
     (with-environment 
      (augment-environment (procedure-environment iter) (cons 'new-ctr new-ctr))
      (set! ctr new-ctr)))))

(define (iterator-copy iter)
  (let ((new-iter (make-iterator (iterator-obj iter))))
    (set! (iterator-ctr new-iter) (iterator-ctr iter))
    new-iter))
</pre>

<p>
After all that, the copy function simply returns its argument if passed a closure.
</p>
</div>

<!-- this doesn't combine in the way you'd want in an object system; if we
     (iterator-copy filter-iterator), the environment of the copy has
         ((filter . #-closure-))
         ((iterator . #-closure-))
         ((obj . #(0 1 2 3 4 5 6 7 8 9)) (func . #-closure-))
     so 'ctr' is not defined in the filter-iterator environment.
-->

<div class="indented">
<p>I don't know why this pleases me so much, but you can use make-iterator
to define a function whose argument takes a different default value each time it is called:
</p>

<pre class="indented">
&gt; (let ((iter (make-iterator #(10 9 8 7 6 5))))
     (define* (func (val (iter))) 
       val)
     (list (func) (func 32) (func) (func)))
&gt; (10 32 8 7)
</pre>
</div>

</blockquote>





<div class="header" id="multidimensionalvectors"><h4>multidimensional vectors</h4></div>


<p>
s7 supports
vectors with any number of dimensions.  It is here, in particular, that generalized
set! shines.  make-vector's second argument can be a list of dimensions, rather than
an integer as in the one dimensional case:
</p>

<pre class="indented">
(make-vector (list 2 3 4))
(make-vector '(2 3) 1.0)
(vector-dimensions (make-vector (list 2 3 4))) -&gt; (2 3 4)
</pre>

<p>The second example includes the optional initial element.
<code>(vect i ...)</code> or <code>(vector-ref vect i ...)</code> return the given
element, and <code>(set! (vect i ...) value)</code> and <code>(vector-set! vect i ... value)</code>
set it.  vector-length (or just length) returns the total number of elements.
vector-dimensions returns a list of the dimensions.
</p>

<pre class="indented">
&gt; (define v (make-vector '(2 3) 1.0))
#2D((1.0 1.0 1.0) (1.0 1.0 1.0))
&gt; (set! (v 0 1) 2.0)
#2D((1.0 2.0 1.0) (1.0 1.0 1.0))
&gt; (v 0 1)
2.0
&gt; (vector-length v)
6
</pre>

<p>This function initializes each element of a multidimensional vector:
</p>

<pre class="indented">
(define (make-array dims . inits)
  (make-shared-vector (apply vector (flatten inits)) dims))

&gt; (make-array '(3 3) '(1 1 1) '(2 2 2) '(3 3 3))
#2D((1 1 1) (2 2 2) (3 3 3))
</pre>

<p>make-vector also takes an optional fourth argument.  If it is #t, and the initial-value
is either an integer or a real, make-vector produces a homogenous vector, a vector that
can only hold elements of the same type as the initial value (either s7_Int or s7_Double
internally).  Homogenous vectors are mostly useful in conjunction with C code.  Three
homogenous float vector functions are currently built-in:
</p>

<pre class="indented">
(<em class=def>float-vector?</em> obj)
(<em class=def>float-vector</em> . args)
(<em class=def>make-float-vector</em> len (init 0.0))
</pre>

<p>To access a vector's elements with different dimensions than the original had, use 
<code>(make-shared-vector original-vector new-dimensions (offset 0))</code>:
</p>

<pre class="indented">
&gt; (let ((v1 #2d((1 2 3) (4 5 6)))) 
    (let ((v2 (make-shared-vector v1 '(6)))) ; flatten the original
      v2))
#(1 2 3 4 5 6)

&gt; (let ((v1 #(1 2 3 4 5 6))) 
    (let ((v2 (make-shared-vector v1 '(3 2)))) 
      v2))
#2D((1 2) (3 4) (5 6))
</pre>
<blockquote>

<div class="indented">

<p>matrix multiplication:
</p>

<pre>
(define (matrix-multiply A B)
  ;; assume square matrices and so on for simplicity
  (let* ((size (car (vector-dimensions A)))
	 (C (make-vector (list size size) 0)))
    (do ((i 0 (+ i 1)))
	((= i size) C)
      (do ((j 0 (+ j 1)))
	  ((= j size))
	(let ((sum 0))
	  (do ((k 0 (+ k 1)))
	      ((= k size))
	    (set! sum (+ sum (* (A i k) (B k j)))))
	  (set! (C i j) sum))))))
</pre>
</div>


<div class="indented">

<p>Conway's game of Life:
</p>

<pre>
(define* (life (width 40) (height 40))
  (let ((state0 (make-vector (list width height) 0))
	(state1 (make-vector (list width height) 0)))

    ;; initialize with some random pattern
    (do ((x 0 (+ x 1)))
	((= x width))
      (do ((y 0 (+ y 1)))
	  ((= y height))
	(set! (state0 x y) (if (&lt; (random 100) 15) 1 0))))

    (do () ()
      ;; show current state (using terminal escape sequences, borrowed from the Rosetta C code)
      (format *stderr* "~C[H" #\escape)           ; ESC H = tab set
      (do ((y 0 (+ y 1)))
	  ((= y height))
	(do ((x 0 (+ x 1)))
	    ((= x width))
	  (if (zero? (state0 x y))
	      (format *stderr* "  ")              ; ESC 07m below = inverse
	      (format *stderr* "~C[07m  ~C[m" #\escape #\escape)))
	(format *stderr* "~C[E" #\escape))        ; ESC E = next line

      ;; get the next state
      (do ((x 1 (+ x 1)))
	  ((= x (- width 1)))
	(do ((y 1 (+ y 1)))
	    ((= y (- height 1)))
	  (let ((n (+ (state0 (- x 1) (- y 1))
		      (state0    x    (- y 1))
		      (state0 (+ x 1) (- y 1))
		      (state0 (- x 1)    y)      
		      (state0 (+ x 1)    y)      
		      (state0 (- x 1) (+ y 1))
		      (state0    x    (+ y 1))
		      (state0 (+ x 1) (+ y 1)))))
	    (set! (state1 x y) 
		  (if (or (= n 3) 
			  (and (= n 2)
			       (not (zero? (state0 x y)))))
		      1 0)))))
      (do ((x 0 (+ x 1)))
	  ((= x width))
	(do ((y 0 (+ y 1)))
	    ((= y height))
	  (set! (state0 x y) (state1 x y)))))))
</pre>
</div>


<div class="indented">

<p>Multidimensional vector constant syntax is modelled after CL: #nd(...) or #nD(...) 
signals that the lists specify the elements of an 'n' dimensional vector: <code>#2D((1 2 3) (4 5 6))</code>
</p>

<pre class="indented">
&gt; (vector-ref #2D((1 2 3) (4 5 6)) 1 2)
6
&gt; (matrix-multiply #2d((-1 0) (0 -1)) #2d((2 0) (-2 2)))
#2D((-2 0) (2 -2))
</pre>

<p>If any dimension has 0 length, you get an n-dimensional empty vector.  It is not
equal to a 1-dimensional empty vector.
</p>

<pre class="indented">
&gt; (make-vector '(10 0 3))
#3D()
&gt; (equal? #() #3D())
#f
</pre>
</div>


<div class="indented">

<p>To save on costly parentheses, and make it easier to write generic multidimensional sequence functions,
you can use this same syntax with lists.
</p>

<pre class="indented">
&gt; (let ((L '((1 2 3) (4 5 6))))
    (L 1 0))              ; same as (list-ref (list-ref L 1) 0) or ((L 1) 0)
4

&gt; (let ((L '(((1 2 3) (4 5 6)) ((7 8 9) (10 11 12))))) 
    (set! (L 1 0 2) 32)   ; same as (list-set! (list-ref (list-ref L 1) 0) 2 32) which is unreadable!
    L)
(((1 2 3) (4 5 6)) ((7 8 32) (10 11 12)))
</pre>

<p>Or with vectors of vectors, of course:
</p>

<pre class="indented">
&gt; (let ((V #(#(1 2 3) #(4 5 6)))) 
    (V 1 2))              ; same as (vector-ref (vector-ref V 1) 2) or ((V 1) 2)
6

&gt; (let ((V #2d((1 2 3) (4 5 6))))
    (V 0))
#(1 2 3)
</pre>

<p>There's one difference between a vector-of-vectors and a multidimensional vector:
in the latter case, you can't clobber one of the inner vectors. 
</p>

<pre class="indented">
&gt; (let ((V #(#(1 2 3) #(4 5 6)))) (set! (V 1) 32) V)
#(#(1 2 3) 32)

&gt; (let ((V #2d((1 2 3) (4 5 6)))) (set! (V 1) 32) V)
;not enough args for vector-set!: (#2D((1 2 3) (4 5 6)) 1 32)
</pre>
</div>



<div class="indented">

<p>Using lists to display the inner vectors may not be optimal, especially when the elements are also lists:
</p>

<pre class="indented">
#2D(((0) (0) ((0))) ((0) 0 ((0))))
</pre>

<p>The "#()" notation is no better (the elements can be vectors), and I'm not a fan of "[]" parentheses.
Perhaps we could use different colors?  Or different size parentheses?
</p>

<pre class="indented">
#2D<em class=green>(</em><em class=red>(</em>(0) (0) ((0))<em class=red>)</em> <em class=red>(</em>(0) 0 ((0))<em class=red>)</em><em class=green>)</em>
#2D<em class="bigger">(</em><em class="big">(</em>(0) (0) ((0))<em class="big">)</em> <em class="big">(</em>(0) 0 ((0))<em class="big">)</em><em class="bigger">)</em>
</pre>

<p>A similar problem afflicts homogenous vectors.  We need some reasonable way to express
such a vector even when it has more than one dimension.  My first thought was <code>#(...)#</code>,
but that makes <code>(let ((b1 0)) (#(1 2)#b1))</code> ambiguous.
</p>

</div>



<div class="indented">

<p>I'm not sure how to handle vector-&gt;list and list-&gt;vector in the multidimensional case.
Currently, vector-&gt;list flattens the vector, and list-&gt;vector always returns a
one dimensional vector, so the two are not inverses.
</p>

<pre class="indented">
&gt; (vector-&gt;list #2d((1 2) (3 4)))
(1 2 3 4)             ; should this be '((1 2) (3 4)) or '(#(1 2) #(3 4))?
&gt; (list-&gt;vector '(#(1 2) #(3 4))) ; what about '((1 2) (3 4))?
#(#(1 2) #(3 4))      
</pre>

<p>
This also affects format and sort!:
</p>

<pre class="indented">
&gt; (format #f "~{~A~^ ~}" #2d((1 2) (3 4)))
"1 2 3 4"

&gt; (sort! #2d((1 4) (3 2)) &gt;) 
#2D((4 3) (2 1))
</pre>

<p>Perhaps make-shared-vector can help:
</p>

<pre class="indented">
&gt;(make-shared-vector (list-&gt;vector '(1 2 3 4)) '(2 2))
#2D((1 2) (3 4))
</pre>

</div>

<div class="indented">

<p>Another question: should we accept the multi-index syntax in a case such as:
</p>

<pre class="indented">
(let ((v #("abc" "def"))) 
  (v 0 2))
</pre>

<p>My first thought was that the indices should all refer to the same
type of object, so s7 would complain in a mixed case like that.
If we can nest any applicable objects and apply the whole thing to
an arbitrary list of indices, ambiguities arise:
</p>

<pre class="indented">
((lambda (x) x) "hi" 0) 
((lambda (x) (lambda (y) (+ x y))) 1 2)
</pre>

<p>I think these should complain that the function got too many arguments,
but from the implicit indexing point of view, they could be interpreted
as:
</p>

<pre class="indented">
(string-ref ((lambda (x) x) "hi") 0) ; i.e. (((lambda (x) x) "hi") 0)
(((lambda (x) (lambda (y) (+ x y))) 1) 2)
</pre>

<p>Add optional and rest arguments, and you can't tell who is supposed to
take which arguments.  
Currently, you can mix types with implicit indices,
but a function grabs all remaining indices.  Trickier than I expected!
</p>

</div>

</blockquote>






<div class="header" id="hashtables"><h4>hash-tables</h4></div>


<ul>
<li>(<em class=def id="makehashtable">make-hash-table</em> (size 512) eq-func) or (make-hash-table eq-func size)
<li>(<em class=def id="hashtable">hash-table</em> ...)
<li>(<em class=def id="hashtableref">hash-table-ref</em> ht key)
<li>(<em class=def id="hashtableset">hash-table-set!</em> ht key value)
<li>(<em class=def id="hashtablep">hash-table?</em> obj)
<li>(<em class=def id="hashtablesize">hash-table-size</em> ht)
<li>(<em class=def id="hashtableiterator">make-hash-table-iterator</em> ht)
<li>(<em class=def id="hashtableiteratorp">hash-table-iterator?</em> obj)
</ul>

<p>
Any s7 object can be the key or the key's value.
Each hash-table keeps track of the keys it contains, optimizing the search wherever possible.
If you know what equality function you want, you can override this optimization by passing that function
as the second or third argument to make-hash-table (the odd way of handling arguments here is r7rs's fault).
If you pass a table size that is not a power of 2, make-hash-table rounds it up to the next power of 2.
</p>

<pre class="indented">
&gt; (let ((ht (make-hash-table)))
    (set! (ht "hi") 123)
    (ht "hi"))
123
</pre>

<p>hash-table (the function) parallels (the functions) vector, list, and string.  Its arguments are cons's containing key/value pairs.
The result is a new hash-table with those values preinstalled: <code>(hash-table '("hi" . 32) '("ho" . 1))</code>.
make-hash-table-iterator returns a function of no arguments (a "thunk").  Each time you call this function, it
returns the next entry in the hash table.  When it runs out of entries, it returns nil.  hash-table-iterator?
returns #t if passed one of these iterators.
</p>


<blockquote>

<div class="indented">

<p>Since hash-tables accept the same applicable-object syntax that vectors use, we can 
treat a hash-table as, for example, a sparse array:
</p>

<pre class="indented">
&gt; (define make-sparse-array make-hash-table)
make-sparse-array

&gt; (let ((arr (make-sparse-array)))
   (set! (arr 1032) "1032")
   (set! (arr -23) "-23")
   (list (arr 1032) (arr -23)))
("1032" "-23")
</pre>
</div>


<div class="indented">

<p>map and for-each accept hash-table arguments. On each iteration, the map or for-each function is passed
an entry, <code>'(key . value)</code>, in whatever order the entries are encountered in the table.  (Both use
make-hash-table-iterator internally).
</p>

<pre class="indented">
(define (hash-table-&gt;alist table)
  (map values table))

(define (merge-hash-tables . tables)
  (apply hash-table 
    (apply append 
      (map hash-table-&gt;alist tables))))
</pre>

<p>reverse of a hash-table returns a new table with the keys and values reversed.
<code>(fill! table ())</code> removes all entries from the hash-table.
</p>

<p>Two hash-tables are equal if they have the same keys with the same values.  This is independent
of the table sizes, or the order in which the key/value pairs were added.
</p>
</div>


<div class="indented">
<p>If the hash key is a float (a non-rational number), hash-table-ref uses <a href="#morallyequalp">morally-equal?</a>.
Otherwise, for example, you could use NaN as a key, but then never be able to access it!
</p>
</div>


<div class="indented">
<pre>
(define-macro (define-memoized name&amp;arg . body)
  (let ((arg (cadr name&amp;arg))
	(memo (gensym "memo")))
    `(define ,(car name&amp;arg)
       (let ((,memo (<em class=red>make-hash-table</em>)))
	 (lambda (,arg)
	   (or (,memo ,arg)                             ; check for saved value
	       (set! (,memo ,arg) (begin ,@body)))))))) ; set! returns the new value

&gt; (define (fib n) 
  (if (&lt; n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
fib
&gt; (define-memoized 
   (memo-fib n) 
     (if (&lt; n 2) n (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))
memo-fib
&gt; (time (fib 34))         ; un-memoized time
1.168                        ;   0.70 on ccrma's i7-3930 machines
&gt; (time (memo-fib 34))    ; memoized time
3.200e-05

&gt; (environment-&gt;list (outer-environment (procedure-environment memo-fib)))
(({memo}-18 . #&lt;hash-table 
    (0 . 0) (1 . 1) (2 . 1) (3 . 2) (4 . 3) (5 . 5) 
    (6 . 8) (7 . 13) (8 . 21) (9 . 34) (10 . 55) (11 . 89) 
    (12 . 144) (13 . 233) (14 . 377) (15 . 610) (16 . 987) 
    (17 . 1597) (18 . 2584) (19 . 4181) (20 . 6765) (21 . 10946) 
    (22 . 17711) (23 . 28657) (24 . 46368) (25 . 75025) (26 . 121393) 
    (27 . 196418) (28 . 317811) (29 . 514229) (30 . 832040) (31 . 1346269) 
    (32 . 2178309) (33 . 3524578) (34 . 5702887)&gt;))
</pre>
<p>But of course, in real code no-one would ever use recursion to get the Fibonacci numbers!
</p>
<pre class="indented">
(define (glib-fib n)
  (let ((phi (/ (+ 1 (sqrt 5)) 2)))
    (floor (real-part (/ (- (expt phi n) (expt (- 1 phi) n)) (sqrt 5))))))
</pre>
</div>

</blockquote>





<div class="header" id="environments"><h4>environments</h4></div>


<p>An environment holds symbols and their values.  The global environment, for example,
holds all the variables that are defined at the top level.
Environments are first class (and applicable) objects in s7.  
</p>

<pre class="indented">
(<em class=def id="environmentp">environment?</em> obj)              #t if obj is an environment
(<em class=def id="withenvironment">with-environment</em> env . body)   evaluate body in the environment env 
(<em class=def id="outerenvironment">outer-environment</em> env)         the environment that encloses the environment env
(<em class=def id="environmenttolist">environment-&gt;list</em> env)         return the environment bindings as a list of (symbol . value) cons's

(<em class=def id="globalenvironment">global-environment</em>)            the top-level environment
(<em class=def id="currentenvironment">current-environment</em>)           the currently visible variables and their values
(<em class=def id="procedureenvironment">procedure-environment</em> proc)    the environment at the time when proc was defined
(error-environment)             the environment at the point of the last error
(<em class=def id="initialenvironment">initial-environment</em>)           the current environment, but all built-in functions have their original values

(<em class=def id="environment">environment</em> . bindings)        make a new environment with the given bindings
(<em class=def id="augmentenvironment">augment-environment</em> env . bindings-or-envs)   add bindings to env
(<em class=def id="augmentenvironment!">augment-environment!</em> env . bindings-or-env)

(<em class=def id="openenvironment">open-environment</em> env)          mark env as open (see below)
(<em class=def id="openenvironmentp">open-environment?</em> env)

(<em class=def id="environmentref">environment-ref</em> env sym)       these are the explicit forms to get and set an environment variable
(<em class=def id="environmentset">environment-set!</em> env sym val)
</pre>

<div class="indented">
<p>Environments provide a very simple, yet very powerful structure or class mechanism.
As a quick example, here is a structure definition:
</p>

<pre class="indented">
(define* (make-tree (key 0) (left ()) (right ()))
  ;; make a tree structure with 3 fields, and a type indicator
  (environment (cons 'key key) 
	       (cons 'left left) 
	       (cons 'right right)
	       (cons 'type 'tree)))

(define (tree? obj)
  (and (environment? obj)
       (eq? (obj 'type) 'tree)))

&gt; (let ((t1 (make-tree)))
    (format #t "t1 (~A): ~{~A~^ ~}~%" 
	    (if (tree? t1) "a tree" "oops")
	    (map (lambda (x)
		   (if (eq? (car x) 'type)
		       (values) ; don't mention the internal type field
		       x))
	         (environment-&gt;list t1))))
"t1 (a tree): (key . 0) (left) (right)"

;; to access a field, use either environment-ref and -set, or implicit indexing:
&gt; (let ((t1 (make-tree))) (t1 'key))
0
&gt; (let ((t1 (make-tree))) (set! (t1 'key) 32) (t1 'key))
32
&gt; (let ((t1 (make-tree))) (with-environment t1 (set! key 32) key))
</pre>
</div>


<p>with-environment evaluates its body in the given environment,
and augment-environment adds a binding (a symbol and its value) to an environment:
</p>

<pre class="indented">
&gt; (let ((a 1)) 
    (with-environment
        (<em class=red>augment-environment</em>
          (current-environment) ; this has 'a with the value 1 
          (cons 'b 32))         ; add 'b with the value 32
      (+ a b)))
33
</pre>

<p>augment-environment does not change the environment passed to it.  It
just prepends the new bindings, shadowing any old ones,
as if you had called "let".  To add the bindings directly to the environment,
use augment-environment!.  Both of these functions accept nil as the
'env' argument as shorthand for <code>(global-environment)</code>.
Both also accept other environments as well as individual bindings,
adding all the argument's bindings to the new environment.
If you call augment-environment! on a procedure-environment,
whatever happens next is not a bug.
</p>

<blockquote>
<div class="indented">
<p>
Augment-environment is a bad name, but
I'm at a loss for a better one.  If we view an environment as a disembodied let,
akin to viewing a generic function as a disembodied lambda,
these names come to mind:
</p>

<pre class="indented">
environment?          let?, islet
global-environment    rootlet
initial-environment   unlet
with-environment      inlet 
outer-environment     outlet
augment-environment   sublet, make-let(?)
augment-environment!  varlet, let-append(?)
current-environment   valet,  make-begin(?)
error-environment     owlet, triplet, error-let(?)
procedure-environment runlet(?)
environment-&gt;list  let-&gt;list(?)
open-environment      open-let(?)
open-environment?
</pre>

<p>If "let" is no good, what about "lex"?
</p>
</div>
</blockquote>


<p>It is possible in Scheme to redefine built-in functions such as car.
To ensure that some code sees the original built-in function definitions,
wrap it in <code>(with-environment (initial-environment) ...)</code>:
</p>
<pre class="indented">
&gt; (let ((caar 123)) 
    (+ caar (with-environment (initial-environment) 
              (caar '((2) 3)))))
125
</pre>

<p>
with-environment and initial-environment are constants, so you can
use them in any context without worrying about whether they've been redefined.
As mentioned in the macro section, #_&lt;name&gt; is a built-in reader macro
for <code>(with-environment (initial-environment) &lt;name&gt;)</code>,
so for example, #_+ is the built-in + function, no matter what.
<code>(initial-environment)</code> cleans up the current environment whenever it's called,
so you can use it to revert the REPL. 
</p>

<blockquote>

<div class="indented">

<p>
I think these functions can implement the notions of libraries,
separate namespaces, or modules.  
Here's one way: first the library writer just writes his library.
The normal user simply loads it.  The abnormal user worries about everything,
so first he loads the library in a local let to make sure no bindings escape 
to pollute his code, and then he
uses initial-environment to
make sure that none of his bindings pollute the library code:
</p>

<pre class="indented">
(let ()
  (with-environment (initial-environment)
    (load "any-library.scm" (current-environment)) 
    ;; by default load puts stuff in the global environment
    ...))
</pre>

<p>Now Abnormal User can do what he wants with the library entities.
Say he wants to use "lognor" under the name "bitwise-not-or", and
all the other functions are of no interest:
</p>

<pre class="indented">
(augment-environment! (current-environment)
  (cons 'bitwise-not-or 
    (with-environment (initial-environment)
      (load "any-library.scm" (current-environment))
      lognor))) ; lognor is presumably defined in "any-library.scm"
</pre>

<p>Say he wants to make sure the library is cleanly loaded, but all
its top-level bindings are imported into the current environment:
</p>

<pre class="indented">
(augment-environment! (current-environment)
  (with-environment (initial-environment)
    (let ()
      (load "any-library.scm" (current-environment))
      (current-environment)))) ; these are the bindings introduced by loading the library
</pre>

<p>To do the same thing, but prepend "library:" to each name:
</p>

<pre class="indented">
(apply augment-environment! (current-environment)
  (with-environment (initial-environment)
    (let ()
      (load "any-library.scm" (current-environment))
      (map (lambda (binding)
	     (cons (string-&gt;symbol 
		    (string-append "library:" (symbol-&gt;string (car binding))))
		   (cdr binding)))
	    (environment-&gt;list (current-environment))))))
</pre>

<p>That's all there is to it!  Here is the same idea as a macro:
</p>

<pre>
(define-macro (let! init end . body)
  ;; syntax mimics 'do: (let! (vars&amp;values) ((exported-names) result) body)
  ;;   (let! ((a 1)) ((hiho)) (define (hiho x) (+ a x)))
  `(let ,init
     ,@body
     (augment-environment! (outer-environment (current-environment))
       ,@(map (lambda (export)
		`(cons ',export ,export))
	      (car end)))
     ,@(cdr end)))
</pre>

<!--
(define-macro (safe-let! init end . body)
  `(with-environment 
       (#_environment 
	(initial-environment)
	,@(#_map (#_lambda (b) 
		 `(#_cons ',(#_car b) ,(#_cadr b)))
	       init))
     ,@body
     (#_augment-environment! (#_outer-environment (#_current-environment))
	,@(#_map (#_lambda (export)
		 `(#_cons ',export ,export))
	       (#_car end)))
     ,@(#_cdr end)))
-->

</div>

<div class="indented">
<p>Well, almost, darn it.  If the loaded library file sets (via set!) a global value
such as abs, we need to put it back to its original form:
</p>

<pre>
(define (safe-load file)
  (let ((e (with-environment          ; save the environment before loading
	       (initial-environment) 
	     (environment-&gt;list (current-environment)))))
    (<em class=red>load</em> file (current-environment))
    (let ((new-e (with-environment    ; get the environment after loading
		     (initial-environment) 
		   (environment-&gt;list (current-environment)))))
      (for-each                       ; see if any built-in functions were stepped on
       (lambda (sym)
	 (if (not (assoc (car sym) e))
	     (begin
	       (format #t "~S clobbered ~A~%" file (car sym))
	       (apply set! (car sym) (list (cdr (assoc (car sym) new-e)))))))
       new-e))))

;; say libtest.scm has the line (set! abs odd?)

&gt; (safe-load "libtest.scm")
"libtest.scm" clobbered abs
&gt; (abs -2)
2
</pre>
</div>

</blockquote>


<p>open-environment marks its argument, either an environment, a closure, or a c-object
as open.  I need better terminology here!  An open object is one that the
built-in s7 functions handle specially.  If they encounter one in their
argument list, they look in the object for their own name, and call that
function if it exists.  A bare-bones example:
</p>

<pre class="indented">
&gt; (abs (open-environment (environment (cons 'abs (lambda (x) 47)))))
47
</pre>

<p>In CLOS, we'd have to declare a class and a method, then call make-instance,
and then we'd discover that it wouldn't work anyway.
Here we have, in effect, an anonymous instance of an anonymous class.
</p>


<blockquote>
<div class="indented">

<p>Here is yet another object system.  Each class and each instance is an environment.
A class might be thought of as a template for instances, but
there's actually no difference between them.  To make an instance of a class, copy it.  To inherit from
another class, concatenate the environments. To access (get or set) a field or a method, use the implicit
indexing syntax with the field or method name.  To evaluate a form in the context of an instance
(CL's with-slots), use with-environment. To run through all the fields, use map or for-each.
</p>

<pre>
(define-bacro* (define-class class-name inherited-classes (slots ()) (methods ()))
  ;; a bacro is needed so that the calling environment is accessible via outer-environment
  ;;   we could also use the begin/let shuffle, but it's too embarrassing
  `(let ((outer-env (outer-environment (current-environment)))
	 (new-methods ())
	 (new-slots ()))

    (for-each
     (lambda (class)
       ;; each class is a set of nested environments, the innermost (first in the list)
       ;;   holds the local slots which are copied each time an instance is created,
       ;;   the next holds the class slots (global to all instances, not copied);
       ;;   these hold the class name and other such info.  The remaining environments
       ;;   hold the methods, with the localmost method first.  So in this loop, we
       ;;   are gathering the local slots and all the methods of the inherited
       ;;   classes, and will splice them together below as a new class.

       (set! new-slots (append (environment-&gt;list class) new-slots))
       (do ((e (outer-environment (outer-environment class)) (outer-environment e)))
	   ((or (not (environment? e))
		(eq? e (global-environment))))
	 (set! new-methods (append (environment-&gt;list e) new-methods))))
     ,inherited-classes)

     (let ((remove-duplicates 
	    (lambda (lst)         ; if multiple local slots with same name, take the localmost
	      (letrec ((rem-dup
			(lambda (lst nlst)
			  (cond ((null? lst) nlst)
				((assq (caar lst) nlst) (rem-dup (cdr lst) nlst))
				(else (rem-dup (cdr lst) (cons (car lst) nlst)))))))
		(reverse (rem-dup lst ()))))))
       (set! new-slots 
	     (remove-duplicates
	      (append (map (lambda (slot)
			     (if (pair? slot)
				 (cons (car slot) (cadr slot))
				 (cons slot #f)))
			   ,slots)                    ; the incoming new slots, #f is the default value
		      new-slots))))                   ; the inherited slots

    (set! new-methods 
	  (append (map (lambda (method)
			 (if (pair? method)
			     (cons (car method) (cadr method))
			     (cons method #f)))
		       ,methods)                     ; the incoming new methods

		  ;; add an object-&gt;string method for this class (this is already a generic function).
		  (list (cons 'object-&gt;string (lambda* (obj (use-write #t))
				       (if (eq? use-write :readable)    ; write readably
					   (format #f "(make-~A~{ :~A ~W~^~})" 
						   ',class-name 
						   (map (lambda (slot)
							  (values (car slot) (cdr slot)))
							(environment-&gt;list obj)))
				           (format #f "#&lt;~A: ~{~A~^ ~}&gt;" 
					           ',class-name
					           (map (lambda (slot)
						          (list (car slot) (cdr slot)))
						        (environment-&gt;list obj)))))))
		  (reverse! new-methods)))           ; the inherited methods, shadowed automatically

    (let ((new-class (open-environment
                       (apply augment-environment           ; the local slots
		         (augment-environment               ; the global slots
		           (apply environment               ; the methods
			     (reverse new-methods))
		           (cons 'class-name ',class-name)  ; class-name slot
			   (cons 'inherited ,inherited-classes)
			   (cons 'inheritors ()))           ; classes that inherit from this class
		         new-slots))))

      (augment-environment! outer-env                  
        (cons ',class-name new-class)                       ; define the class as class-name in the calling environment

	;; define class-name? type check
	(cons (string-&gt;symbol (string-append (symbol-&gt;string ',class-name) "?"))
	      (lambda (obj)
		(and (environment? obj)
		     (eq? (obj 'class-name) ',class-name)))))

      (augment-environment! outer-env
        ;; define the make-instance function for this class.  
        ;;   Each slot is a keyword argument to the make function.
        (cons (string-&gt;symbol (string-append "make-" (symbol-&gt;string ',class-name)))
	      (apply lambda* (map (lambda (slot)
				    (if (pair? slot)
					(list (car slot) (cdr slot))
					(list slot #f)))
				  new-slots)
		     `((let ((new-obj (copy ,,class-name)))
			 ,@(map (lambda (slot)
				  `(set! (new-obj ',(car slot)) ,(car slot)))
				new-slots)
			 new-obj)))))

      ;; save inheritance info for this class for subsequent define-method
      (letrec ((add-inheritor (lambda (class)
				(for-each add-inheritor (class 'inherited))
				(if (not (memq new-class (class 'inheritors)))
				    (set! (class 'inheritors) (cons new-class (class 'inheritors)))))))
	(for-each add-inheritor ,inherited-classes))
    
      ',class-name)))


(define-macro (define-generic name)    ; (define (genfun any) ((any 'genfun) any))
  `(define ,name 
     (lambda args 
       (let ((gf ((car args) ',name))) ; get local definition
	 (if (not (eq? gf ,name))      ; avoid infinite recursion
             (apply gf args)
	     (error "attempt to call generic function wrapper recursively"))))))


(define-macro (define-slot-accessor name slot)
  `(define ,name (make-procedure-with-setter 
                   (lambda (obj) (obj ',slot)) 
		   (lambda (obj val) (set! (obj ',slot) val)))))


(define-bacro (define-method name-and-args . body)
  `(let* ((outer-env (outer-environment (current-environment)))
	  (method-name (car ',name-and-args))
	  (method-args (cdr ',name-and-args))
	  (object (caar method-args))
	  (class (symbol-&gt;value (cadar method-args)))
	  (old-method (class method-name))
	  (method (apply lambda* method-args ',body)))

     ;; define the method as a normal-looking function
     ;;   s7test.scm has define-method-with-next-method that implements call-next-method here
     ;;   it also has make-instance 
     (augment-environment! outer-env
       (cons method-name 
	     (apply lambda* method-args 
		    `(((,object ',method-name)
		       ,@(map (lambda (arg)
				(if (pair? arg) (car arg) arg))
			      method-args))))))
     
     ;; add the method to the class
     (augment-environment! (outer-environment (outer-environment class))
       (cons method-name method))

     ;; if there are inheritors, add it to them as well, but not if they have a shadowing version
     (for-each
      (lambda (inheritor) 
	(if (not (eq? (inheritor method-name) #&lt;undefined&gt;)) ; defined? goes to the global env
	    (if (eq? (inheritor method-name) old-method)
		(set! (inheritor method-name) method))
	    (augment-environment! (outer-environment (outer-environment inheritor))
   	      (cons method-name method))))
      (class 'inheritors))

     method-name))


(define (all-methods obj method)
  ;; for arbitrary method combinations: this returns a list of all the methods of a given name
  ;;   in obj's class and the classes it inherits from (see example below)
  (let* ((base-method (obj method))
	 (methods (if (procedure? base-method) (list base-method) ())))
    (for-each 
     (lambda (ancestor)
       (let ((next-method (ancestor method)))
	 (if (and (procedure? next-method)
		  (not (memq next-method methods)))
	     (set! methods (cons next-method methods)))))
     (obj 'inherited))
    (reverse methods)))


&gt; (define-class class-1 () 
       '((a 1) (b 2)) 
       (list (list 'add (lambda (obj) 
                          (with-environment obj
                            (+ a b))))))
class-1
&gt; (define v (make-class-1 :a 32))
v 
&gt; (v 'a)                         ; to set the 'a slot, (set! (v 'a) 0) 
32
&gt; (object-&gt;string v)             ; built-in functions are all generic
"#&lt;class-1: (a 32) (b 2)&gt;"       ;   so this uses the method defined in the class definition
&gt; ((v 'add) v)
34
&gt; (define-generic add)
add
&gt; (add v)                        ; syntactic sugar for ((v 'add) v)
34
&gt; (define-slot-accessor slot-a a) ; more sugar!
slot-a
&gt; (slot-a v)                     ; same as (v 'a), set via (set! (slot-a v) 123)
32
&gt; (map car v)                    ; map and for-each work with environments
(a b)                               ;   map cdr would return '(32 2) in this case
&gt; (define-class class-2 (list class-1)
       '((c 3)) 
       (list (list 'multiply (lambda (obj) 
                               (with-environment obj 
                                 (* a b c))))))
class-2
&gt; (define v2 (make-class-2 :a 32))
v2
&gt; v2                            ; will use object-&gt;string
"#&lt;class-2: (c 3) (a 32) (b 2)&gt;"
&gt; ((v2 'multiply) v2)
192
&gt; (add v2)                      ; inherited from class-1
34
&gt; (define-method (subtract (obj class-1)) (with-environment obj (- a b)))
subtract
&gt; (subtract v2)  ; class-2 inherits from class-1 so it knows about subtract
30
&gt; (define v1 (make-class-1))
v1
&gt; (augment-environment! v1      ; change the add method just in this instance
       (cons 'add (lambda (obj) 
                    (with-environment obj
                      (+ 1 a (* 2 b))))))
#&lt;class-1: (a 1) (b 2) (add #&lt;lambda (obj)&gt;)&gt;
&gt; (add v1)
6
&gt; (add v)                       ; other class-1 instances are not affected
34
&gt; (define-class class-3 (list class-2) () 
    (list (list 'multiply (lambda (obj num) 
			    (* num 
			       ((class-2 'multiply) obj) ; method combination 
			       (add obj))))))
class-3
&gt; ((class-3 'multiply) class-3 10)
180                               ; (* 10 (* 1 2 3) (+ 1 2))
&gt; (define v3 (make-class-3))
v3
&gt; (all-methods v3 'multiply)
(#&lt;lambda (obj num)&gt; #&lt;lambda (obj)&gt;)
&gt; (for-each (lambda (p) (format #t "~A~%" (procedure-source p))) (all-methods v3 'multiply))
(lambda (obj num) (* num ((class-2 'multiply) obj) (add obj)))
(lambda (obj) (with-environment obj (* a b c)))


;; another obvious possibility: generic macros
</pre>

<p>with-environment (used briefly above) provides an even more striking simplification of syntax
than implicit indexing or multidimensional vectors, and it is faster as well!
See Snd's generators.scm for many examples.  
</p>

<!--
at class definition time:
    (list 'mac (symbol->value (define-macro (mac a) `(+ ,a 1))))
-->
</div>

<div class="indented">
<p>As shown in the preceding example, implicit indexing of a local environment
does not search the global environment.  Since initial-environment extends the
current environment chain, it is considered a local environment:
</p>

<pre class="indented">
&gt; ((global-environment) 'abs)
abs
&gt; (let () ((current-environment) 'abs))
#&lt;undefined&gt;
&gt; ((initial-environment) 'abs) ; what a bad function name
#&lt;undefined&gt;
</pre>

</div>


<div class="indented">
<pre>
(define-bacro (value-&gt;symbol val)
   ;; (outer-environment (current-environment)) is the calling environment
  `(call-with-exit
    (lambda (return)
      (do ((e (current-environment) (outer-environment e))) ()
	(for-each 
	 (lambda (slot)
	   (if (equal? ,val (cdr slot))
	       (return (car slot))))
	 e)
	(if (eq? e (global-environment))
	    (return #f))))))

&gt; (let ((a 1) (b "hi")) 
    (value-&gt;symbol "hi"))
b
</pre>
</div>


<div class="indented">
<p>Scheme needs a way to define functions that share a closure.
Here's an idle thought:
</p>

<pre class="indented">
(define f1 (let ((x 23))
	     (lambda (a)
	       (+ x a))))
(define (f2 b)
  (+ b (* 2 ((procedure-environment f1) 'x)))) ; import f1's x into f2

&gt; (+ (f1 1) (f2 1))
71
</pre>
<p>That has now blossomed into...
</p>
</div>


<div class="indented">
<p>open-environment alerts the rest of s7 that the environment has methods.
</p>

<pre>
(begin
  (define float-vector? #f)
  (define make-float-vector #f)
  
  (let ((type (gensym))
	(-&gt;float (lambda (x)
		   (if (real? x)
		       (* x 1.0)
		       (error 'wrong-type-arg "float-vector new value is not a real: ~A" x)))))

    (augment-environment! (current-environment)
      (cons 'length (lambda (p) ((procedure-environment p) 'len)))
      (cons 'object-&gt;string (lambda (p) "#&lt;float-vector&gt;")))

    (set! make-float-vector
	  (lambda* (len (init 0.0)) 
	    (let ((obj (make-vector len (-&gt;float init))))
	      (<em class=red>open-environment</em>
	        (make-procedure-with-setter
		  (lambda (i) (#_vector-ref obj i))
		  (lambda (i val) (#_vector-set! obj i (-&gt;float val))))))))
    
    (set! float-vector?
	  (lambda (p)
	    (and (procedure? p)
		 (eq? ((procedure-environment p) 'type) type))))))
  
&gt; (define fv (make-float-vector 32))
fv
&gt; fv
#&lt;float-vector&gt;
&gt; (length fv)
32
&gt; (set! (fv 0) 123)
123.0
&gt; (fv 0)
123.0
</pre>

<p>If we add the following lines to the augment-environment! section above:
</p>

<pre class="indented">
(cons 'vector? (lambda (p) #t)) 
(cons 'vector-length (lambda (p) ((procedure-environment p) 'len)))
(cons 'vector-dimensions (lambda (p) (list ((procedure-environment p) 'len))))
(cons 'vector-ref (lambda (p ind) (#_vector-ref ((procedure-environment p) 'obj) ind)))
(cons 'vector-set! (lambda (p ind val) (#_vector-set! ((procedure-environment p) 'obj) ind (-&gt;float val))))
(cons 'vector-fill! (lambda (p val) (#_vector-fill! ((procedure-environment p) 'obj) (-&gt;float val))))
(cons 'fill! (lambda (p val) (#_vector-fill! ((procedure-environment p) 'obj) (-&gt;float val))))
(cons 'vector-&gt;list (lambda (p) (#_vector-&gt;list ((procedure-environment p) 'obj))))
(cons 'reverse (lambda (p) (#_reverse ((procedure-environment p) 'obj))))
</pre>

<p>then our float-vectors are fully legitimate Scheme vectors. It is irrelevant to Scheme that
they happen to be procedures; a vector is any value that behaves like a vector.
Extend this to math ops, and we can treat float-vectors as matrices, so <code>(* v1 v2)</code>
is matrix multiplication.  Or add quaternions, gap-buffers as strings &mdash; I'd say "the possibilities
are endless", but actually I can't think of any others right at the moment.
</p>

<p>I can't resist adding at least some of the quaternion implementation.  In the following code
we add quaternions to some of the math functions (finally "number?" is not the same
as "complex?"!), and include support for possible additional numeric types that might be
added later.  As in the earlier case, a number is whatever behaves like a number &mdash;
we aren't bound by any previous classes, and we don't have to define separate methods for every possibility.
The '+' function for instance, can take any mixture of numbers:
</p>

<pre>
(define-class quaternion () 
  '((r 0) (i 0) (j 0) (k 0))
  (list (list 'number? (lambda (obj) #t))
	(list 'complex? (lambda (obj) #f))
	(list 'real? (lambda (obj) #f))
	(list 'integer? (lambda (obj) #f))
	(list 'rational? (lambda (obj) #f))

	(list '+ (lambda orig-args
		   (let add ((r ()) (i ()) (j ()) (k ()) (args orig-args))
		     (if (null? args)
			 (<em class=red>make-quaternion</em> 
                           (apply + r) (apply + i) (apply + j) (apply + k)) 
			 (let ((n (car args)))
			   (cond
			    ((real? n)
			     (add (cons n r) i j k (cdr args)))
			    ((complex? n)
			     (add (cons (real-part n) r) (cons (imag-part n) i) j k (cdr args)))
			    ((<em class=red>quaternion?</em> n)
			       (add (cons (n 'r) r) (cons (n 'i) i) 
                                    (cons (n 'j) j) (cons (n 'k) k) 
                                    (cdr args)))
			    ((<em class=red>open-environment?</em> n) ; maybe we'll add octonions later!
			     (if (eq? n (car orig-args))
                                 ;; if we are not the first argument, and we don't know how to handle the
                                 ;; first argument, then we have to raise an error.  Otherwise, the two
                                 ;; methods will get into an infinite loop saying very politely
                                 ;;   "please, you go first".
				 (error 'missing-method "+ can't handle these arguments: ~A" args)
				 (apply (n '+) 
                                        (make-quaternion 
                                          (apply + r) (apply + i) (apply + j) (apply + k)) 
                                        (cdr args))))
			    (else (error 'wrong-type-arg "+ argument ~A is not a number" n))))))))
	))

&gt; (let ((q1 (make-quaternion 1.0 1.0 0.0 0.0)))
    (+ 1 q1 2.5+i))
#&lt;quaternion: (r 4.5) (i 2.0) (j 0.0) (k 0.0)&gt;
</pre>

</div>
</blockquote>





<div class="header" id="multiplevalues"><h4>multiple-values</h4></div>


<p>
In s7, multiple values are spliced directly into the caller's argument list.
</p>

<pre class="indented">
&gt; (+ (values 1 2 3) 4)
10
&gt; (string-ref ((lambda () (values "abcd" 2))))
#\c
&gt; ((lambda (a b) (+ a b)) ((lambda () (values 1 2))))
3
&gt; (+ (call/cc (lambda (ret) (ret 1 2 3))) 4) ; call/cc has an implicit "values"
10
&gt; ((lambda* ((a 1) (b 2)) (list a b)) (values :a 3))
(3 2)

(define-macro (call-with-values producer consumer) 
  `(,consumer (,producer)))

(define-macro (multiple-value-bind vars expr . body)
  `((lambda ,vars ,@body) ,expr))

(define (curry function . args)
  (if (null? args)
      function
      (lambda more-args
        (if (null? more-args)
            (apply function args)
            (function (apply values args) (apply values more-args))))))
</pre>



<blockquote>

<div class="indented">

<p>There aren't that many real uses for multiple-values in Scheme.  Nearly all can be replaced by
a normal list.  There are a couple of cases where multiple-values are handy.
First, you can use "values" to return any number of values, including 0,
from map's function application:
</p>

<pre class="indented">
&gt; (map (lambda (x) (if (odd? x) (values x (* x 20)) (values))) (list 1 2 3))
(1 20 3 60)

&gt; (map values (list 1 2 3) (list 4 5 6))
(1 4 2 5 3 6)

(define (remove-if func lst) 
  (map (lambda (x) (if (func x) (values) x)) lst))

(define (pick-mappings func lst)          
  (map (lambda (x) (or (func x) (values))) lst))

(define (shuffle . args) 
  (apply map values args))

&gt; (shuffle '(1 2 3) #(4 5 6) '(7 8 9))
(1 4 7 2 5 8 3 6 9)

(define (concatenate . args)
  (apply append (map (lambda (arg) (map values arg)) args)))
</pre>

<p>
Second, you can use multiple-values to turn off the short-circuit evaluation
of 'or' and 'and'.  
</p>

<pre class="indented">
&gt; (let ((x 1)) (and (<em class=red>values</em> #f (let () (set! x 3) #f))) x)
3
</pre>

<p>But 'apply' has the same effect and is easier to read:
</p>

<pre class="indented">
(define (and? . args) (apply and args))
(define (every? f . seqs) (apply and (apply map f seqs)))
</pre>

<p>More often you want to keep the short-circuiting, but add some action as
'and' or 'or' marches through its arguments:
</p>

<pre class="indented">
(define-macro (every? function . args)
  `(and ,@(map (lambda (arg) `(,function ,arg)) args)))

(define (map-and proc lst) 
  (or (null? lst) 
      (and (proc (car lst)) 
           (map-and proc (cdr lst)))))

(define-macro (and-let* vars . body)
  `(let () ;; bind vars, if any is #f stop, else evaluate body with those bindings
     (and ,@(map (lambda (var) `(begin (apply define ',var) ,(car var))) vars) 
          (begin ,@body))))
</pre>

<p>Finally, a macro can return multiple values; these are evaluated and spliced,
exactly like a normal macro,
so you can use <code>(values '(define a 1) '(define b 2))</code> to
splice multiple definitions at the macro invocation point.  
</p>

<p>At the top-level (in the REPL), since there's nothing to splice into, you simply get your values back:
</p>

<pre class="indented">
&gt; (values 1 (list 1 2) (+ 3 4 5))
(values 1 (1 2) 12)
</pre>

<p>But this printout is just trying to be informative.  There is no multiple-values object
in s7.  You can't <code>(set! x (values 1 2))</code>, for example.  The values function
tells s7 that its arguments should be handled in a special way, and the multiple-value indication goes away
as soon as the arguments are spliced into some caller's arguments.  
</p>

<p>Internally, s7 uses <code>(apply values ...)</code> to implement unquote splicing (",@") in quasiquote.
</p>
</div>


<div class="indented">

<p>In some Schemes, values behaves like CL's prog1:
</p>

<pre class="indented">
(not s7)&gt; (let ((x 1)) (cond ((values #f (set! x 2) #t) 3) (#t x)))
2
(not s7)&gt; (if (values #f #t) 1 2)
2
</pre>

<p>But in s7 we're trying to implement real multiple values (else why have them at all?).
There are many ways we could interpret <code>(cond ((values ...))...)</code> and
<code>(cond ((values...) =&gt; func))</code>, but surely
equivalent uses of "cond" and "if" should give the same result.
Currently in s7, where a test is in progress, only <code>(values #f)</code> is the same as #f.
</p>

<pre class="indented">
&gt; (if (values #f #f) 1 2)            ; (values #f #f) is not #f
1
&gt; (cond ((values #f #f) 1) (#t 2))
1
;;; but if we interpreted this as splicing in the values, we get an inconsistency:
&gt; (cond (#f #f 1) (#t 2))
2

&gt; (if (values #f) 1 2)
2
&gt; (cond ((values #f) 1) (#t 2))
2

&gt; (if (values) 1 2)
1
&gt; (cond ((values) 1) (#t 2))
1
;;; this is consistent with (cond (1) (#t 2))
</pre>

<p>
So "if" and "cond" agree, but it requires that in one case the "values"
behavior is slightly weird.  <code>(or (values #f #f))</code> is #f, but that isn't inconsistent because
"or" is not testing anything.
We might choose to say that <code>(if (values #f #f)...)</code>
is an error, but that would be hasty &mdash;
our troubles have only begun.  First, "cond" can omit the expressions that follow the test, unlike "if":
</p>

<pre class="indented">
&gt; (cond (3))
3
</pre>

<p>and even trickier, "cond" can pass the test value to a function:
</p>

<pre class="indented">
&gt; (cond (3 =&gt; +))
3
</pre>

<p>The various standards agree that in the "=&gt;" case, the "fed to" function
receives one argument, so
</p>

<pre class="indented">
(not s7)&gt; (cond ((values 1 2) =&gt; +))
1
</pre>

<p>If we were following the "splice immediately" model, this would be <code>(cond (1 2 =&gt; +))</code>
which is an error in some Schemes.
So something has to give.  My druthers is to make "values" work as consistently as possible, and hope
that the one odd corner will not trip anyone.  From that point of view, the "one arg" standard
looks like a wasted opportunity.
s7 handles it this way:
</p>

<pre class="indented">
&gt; (+ 1 (cond ((values 2 3))) 4)   ; trailing values are not ignored
10
&gt; (cond ((values 1 2 3) =&gt; +))
6
</pre>

<p>Of course, it is unproblematic that the expression can itself involve multiple values:
</p>

<pre class="indented">
&gt; (+ (cond (#t (values 1 2))))
3
</pre>

<p>Now, what have I missed?
</p>
</div>


<div class="indented">

<p>Since set! does not evaluate its first argument, and
there is no setter for "values", <code>(set! (values x) ...)</code> is not
the same as <code>(set! x ...)</code>.  <code>(string-set! (values string) ...)</code>
works because string-set! does evaluate its first argument.  <code>((values + 1 2) (values 3 4) 5)</code>
is 15, as anyone would expect.
</p>
</div>


<div class="indented">

<p>I wrote all that and said "nobody needs multiple values!".  In desperation,
</p>

<table><tr><td>
<div class="bluishbordered">
<pre>
(define (flatten lst)
  (define (flatten-1 lst)
    (cond ((null? lst) (values))
	  ((not (pair? lst)) lst)
	  (#t (values (flatten-1 (car lst))
		      (flatten-1 (cdr lst))))))
  (map values (list (flatten-1 lst))))
</pre>
</div>
</td>
<td></td>

<td>
<div class="brownishbordered">
<pre>
(define (boring-flatten x)
  (cond ((null? x) ())
        ((not (pair? x)) (list x))
        (#t (append (boring-flatten (car x))
		    (boring-flatten (cdr x))))))
</pre>
</div>
</td>
</tr>
</table>

<p>Here's a much more entertaining version:
</p>
<pre>
(define (flatten! lst) ; in-place flatten
  (let loop ((L lst))
    (if (pair? (car L))
	(let ((end (cdr L))
	      (p (car L)))
	  (set! (car L) (car p))
	  (set! (cdr L) (cdr p))
	  (set! (cdr (list-tail L (- (length p) 1))) end)
	  (loop L))
	(if (not (null? (cdr L)))
	    (if (null? (car L))
		(begin
		  (set! (car L) (cadr L))
		  (set! (cdr L) (cddr L))
		  (loop L))
		(loop (cdr L)))))
    (if (equal? lst '(()))
	()
	(let ((len (length lst)))
	  (if (null? (car (list-tail lst (- len 1))))
	      (set! (cdr (list-tail lst (- len 2))) ()))
	  lst))))
</pre>
</div>

</blockquote>

<!-- one place where multiple values might cause surprise:
    :(define* (a1 (a2 (values 1 2))) a2)
    :(a1)
    (values 1 2)
    :(define (a1 a2) a2)
    :(a1 (values 1 2))
    ;(values 1 2): too many arguments: (values 1 2)
-->





<div class="header" id="callwithexit1"><h4>call-with-exit, with-baffle and continuation?</h4></div>


<p><b><em class=def id="callwithexit">call-with-exit</em></b> is call/cc without the ability to jump back into the original context,
similar to "return" in C.  This 
is cleaner than call/cc, and much faster. 
</p>

<pre class="indented">
(define-macro (block . body) 
  ;; borrowed loosely from CL &mdash; predefine "return" as an escape
  `(<em class=red>call-with-exit</em> (lambda (return) ,@body)))

(define-macro (while test . body)
  ;; while loop with predefined break and continue
  `(<em class=red>call-with-exit</em>
    (lambda (break) 
      (letrec ((continue (lambda () 
			   (if (let () ,test)
			       (begin 
				 (let () ,@body)
				 (continue))
			       (break)))))
	(continue)))))

(define (and-for-each func . args)
  ;; apply func to the first member of each arg, stopping if it returns #f
  (<em class=red>call-with-exit</em>
   (lambda (quit)
     (apply for-each (lambda arglist
		       (if (not (apply func arglist))
			   (quit #&lt;unspecified&gt;))) 
	    args))))

(define (find-if f . args)  ; generic position-if is very similar
  (<em class=red>call-with-exit</em>
   (lambda (return) 
     (apply for-each (lambda main-args 
		       (if (apply f main-args) 
			   (apply return main-args)))
	    args))))

&gt; (find-if even? #(1 3 5 2))
2
&gt; (* (find-if > #(1 3 5 2) '(2 2 2 3)))
6
</pre>

<p>
The call-with-exit function's argument (the "continuation") is only valid
within the call-with-exit function.  In call/cc, you can save it, then call it later
to jump back, but if you try that with call-with-exit (from outside the call-with-exit function's body), you'll get an error.
This is similar to trying to read from a closed input port. 
</p>


<p>The other side, so to speak, of call-with-exit, is <em class=def id="withbaffle">with-baffle</em>.
Both limit the scope of a continuation.
Sometimes we need a normal call/cc, but want to make sure it is active
only within a given block of code.  
Normally, if a continuation gets away, there's no telling when it might wreak havoc on us.
Scheme code with call/cc becomes unpredictable, undebuggable, and completely
unmaintainable.  
with-baffle blocks all that &mdash; no continuation can jump into its body:
</p>

<pre class="indented">
(let ((what's-for-breakfast ())
      (bad-dog 'fido))        ; bad-dog wonders what's for breakfast?
  (<em class=red>with-baffle</em>                ; the syntax is (with-baffle . body)         
   (set! what's-for-breakfast
	 (call/cc
	  (lambda (biscuit?)
	    (set! bad-dog biscuit?) ; bad-dog smells a biscuit!
	    (biscuit? 'biscuit!)))))
  (if (eq? what's-for-breakfast 'biscuit!) 
      (bad-dog 'biscuit!))     ; now, outside the baffled block, bad-dog wants that biscuit!
  what's-for-breakfast)        ;   but s7 says "No!": baffled! ("continuation can't jump into with-baffle")
</pre>

<br>
<p><em class=def id="continuationp">continuation?</em> returns #t if its argument is a continuation,
as opposed to a normal procedure.  I don't know why Scheme hasn't had this function from
the very beginning, but it's needed if you want to write a continuable error
handler.  Here is a sketch of the situation:
</p>

<pre class="indented">
(let ()
  (catch #t
	 (lambda ()
	   (let ((res (call/cc 
                        (lambda (ok) 
			  (error 'cerror "an error" ok)))))
	     (display res) (newline)))
	 (lambda args
	   (if (and (eq? (car args) 'cerror)
		    (<em class=red>continuation?</em> (cadadr args)))
	       (begin
		 (display "continuing...")
		 ((cadadr args) 2)))
	   (display "oops"))))

continuing...2
</pre>

<p>In a more general case, the error handler is separate from the
catch body, and needs a way to distinguish a real continuation
from a simple procedure.  Otherwise, it blithely announces that
it is continuing from the point of the error, but then fails to do so.
</p>






<div class="header" id="format1"><h4>format, object-&gt;string</h4></div>


<p>s7's built-in <em class=def id="format">format</em> function is very close to that in srfi-48.
</p>

<pre class="indented">
&gt; (format #f "~A ~D ~F" 'hi 123 3.14)
"hi 123 3.140000"
</pre>


<p>The format directives (tilde chars) are:</p>
<pre class="indented">
~%        insert newline
~&amp;        insert newline if preceding char was not newline
~~        insert tilde
~\n       (tilde followed by newline): trim white space
~{        begin iteration (take arguments from a list, string, vector, or any other applicable object)
~}        end iteration
~^        jump out of iteration
~*        ignore the current argument
~C        print character (numeric argument = how many times to print it)
~P        insert 's' if current argument is not 1 or 1.0 (use ~@P for "ies" or "y")
~A        object-&gt;string as in display
~S        object-&gt;string as in write
~B        number-&gt;string in base 2
~O        number-&gt;string in base 8
~D        number-&gt;string in base 10
~X        number-&gt;string in base 16
~E        float to string, (format #f "~E" 100.1) -&gt; "1.001000e+02", (%e in C)
~F        float to string, (format #f "~F" 100.1) -&gt; "100.100000",   (%f in C)
~G        float to string, (format #f "~G" 100.1) -&gt; "100.1",        (%g in C)
~T        insert spaces (padding)
~W        object-&gt;string with :readable (write readably; s7 is the intended reader)
</pre>

<p>The eight directives before ~W take the usual numeric arguments to specify field width and precision.
</p>
<p>
<code>(format #f ...)</code> simply returns the formatted string; <code>(format #t ...)</code>
also sends it to *stdout*.  To send the string to *stderr* instead, <code>(format *stderr* ...)</code>.
</p>


<blockquote>

<div class="indented">

<p>Floats can occur in any base, so:
</p>

<pre class="indented">
&gt; #xf.c
15.75
</pre>

<p>This also affects format.  In most Schemes, <code>(format #f "~X" 1.25)</code> is
an error.  In CL, it is equivalent to using ~A which is perverse.  But 
</p>

<pre class="indented">
&gt; (number-&gt;string 1.25 16)
"1.4"
</pre>

<p>and there's no obvious way to get the same effect from format unless we accept
floats in the "~X" case.  So in s7, 
</p>

<pre class="indented">
&gt; (format #f "~X" 21)
"15"
&gt; (format #f "~X" 1.25)
"1.4"
&gt; (format #f "~X" 1.25+i)
"1.4+1.0i"
&gt; (format #f "~X" 21/4)
"15/4"
</pre>

<p>That is, the output choice matches the argument.  A case that came up in the Guile mailing lists is:
<code>(format #f "~F" 1/3)</code>.  s7 currently returns "1/3", but Clisp returns "0.33333334".
</p>

<p>The curly bracket directive applies to anything you can map over, not just lists:
</p>

<pre class="indented">
&gt; (format #f "~{~C~^ ~}" "hiho")
"h i h o"
&gt; (format #f "~{~{~C~^ ~}~^...~}" (list "hiho" "test"))
"h i h o...t e s t"
</pre>
</div>


</blockquote>

<p>object-&gt;string returns the string representation of its argument.  Its optional second argument
can be #f (use display), #t (the default, use write), or :readable.  In the latter case, object-&gt;string
tries to produce a string that can be evaluated via eval-string to return an object equal to the
original.
</p>

<pre class="indented">
&gt; (object-&gt;string "hiho")
"\"hiho\""

&gt; (format #f "~S" "hiho")
"\"hiho\""
</pre>


<blockquote>

<div class="indented">

<p>I added object-&gt;string to s7 before deciding to include format.  format excites a
vague disquiet &mdash; why do we need this ancient unlispy thing?
We can almost replace it with:
</p>

<pre class="indented">
(define (objects-&gt;string . objects)
  (apply string-append (map (lambda (obj) (object-&gt;string obj #f)) objects)))
</pre>

<p>But how to handle lists (~{...~} in format), or columnized output (~T)?
I wonder whether formatted string output still matters outside a REPL.  Even in that context,
a modern GUI leaves formatting decisions to a text or table widget.
</p>

<pre class="indented">
(define-macro (string-&gt;objects str . objs)
  `(with-input-from-string ,str
     (lambda ()
       ,@(map (lambda (obj)
		`(set! ,obj (eval (read))))
	      objs))))
</pre>


<!--

:(objects->string "int: " 32 ", string: " "hi")
"int: 32, string: hi"

(define (cycle->string . objs)
  (call-with-exit
   (lambda (return)
     (for-each
      (lambda (obj)
	(if (pair? obj)
	    (return
	     (string-append 
	      (apply objects->string 
		     (map (lambda (obj)
			    (if (pair? obj)
				(car obj)
				obj))
			  objs))
	      (apply cycle->string 
		     (map (lambda (obj)
			    (if (pair? obj)
				(cdr obj)
				obj))
			  objs))))))
      objs)
     "")))

;;; (cycle->string ": " (list 1 2 3) " |")
:(objects->string "int: " 32 ", list with spaces: (" (cycle->string (list 1 2 3) " ") "), string: " "hi")
"int: 32, list with spaces: (1 2 3 ), string: hi"

:(let ((x 0) (y 0)) (string->objects "1 2" x y) (list x y))
(1 2)

-->

</div>

</blockquote>






<div class="header" id="hooks"><h4>hooks</h4></div>

<pre class="indented">
(<em class=def id="makehook">make-hook</em> . fields)           ; make a new hook
(<em class=def id="hookfunctions">hook-functions</em> hook)          ; the hook's list of 'body' functions
</pre>

<p>A hook is a function created by make-hook, and called (normally from C) when something interesting happens.
In GUI toolkits hooks are called callback-lists, in CL conditions,
in other contexts watchpoints or signals.  s7 itself has several
hooks: <a href="#errorhook">*error-hook*</a>, <a href="#unboundvariablehook">*unbound-variable-hook*</a>, and <a href="#loadhook">*load-hook*</a>.
make-hook is:
</p>

<pre class="indented">
(define (make-hook . args)
  (let ((init ())
	(body ())
	(end ()))
    (apply lambda* args
      '(let ((result #&lt;unspecified&gt;))
         (let ((e (current-environment)))
           (dynamic-wind 
	     (lambda () (for-each (lambda (f) (f e)) init))
	     (lambda () (for-each (lambda (f) (f e)) body) result)
	     (lambda () (for-each (lambda (f) (f e)) end)))))
       ())))
</pre>

<p>
Each of the functions held by the hook ('f' above), takes one argument, the environment within the hook,
and its return value is ignored.
The function can use <code>(with-environment arg ...)</code> or <code>(arg symbol)</code> to access the arguments to the hook ('args').
The hook environment's result field is the returned value of the hook application.
Each such environment has three lists,
init, body, and end, and
these lists of functions are called in dynamic-wind.
Here's a sketch:
</p>

<pre class="indented">
(define (add-to-hook hook function)
  (set! (hook-functions hook) (cons function (hook-functions hook))))

&gt; (define h (make-hook '(a 32) 'b)) 
h
&gt; (add-to-hook h (lambda (hook) 
                   (set! (hook 'result) 
                         (format #f "a: ~A, b: ~A" (hook 'a) (hook 'b)))))
(#&lt;lambda (hook)&gt;)
&gt; (h 1 2)
"a: 1, b: 2"
&gt; (h)
"a: 32, b: #f"
</pre>

<p>To add an old-style hook function:
</p>

<pre class="indented">
(add-to-hook hook (lambda (h) (set! (h 'result) (apply func (map h (h 'args))))))
</pre>

<p>In C, to make a hook:
</p>

<pre class="indented">
hook = s7_eval_c_string("(make-hook '(a 32) 'b)");
s7_gc_protect(s7, hook);
</pre>

<p>And call it:
</p>

<pre class="indented">
result = s7_call(s7, hook, s7_list(s7, 2, s7_make_integer(s7, 1), s7_make_integer(s7, 2)));
</pre>

<div class="indented">
<pre>
(define-macro (hook . body)
  `(let ((h (make-hook)))
     (set! (hook-functions h) (list (lambda (h) (set! (h 'result) (begin ,@body)))))
     h))
</pre>
</div>

<p>Hooks are split into three list of functions to reflect the roles that
hook functions play.
Some are "watchers" that simply want notification
that some event has occurred (the 'init' list).
Others want to deal with the
event in some way, possibly returning a result, and possibly interacting
with any other similar hook functions' results (the 'body' list).
Still others are only interested in the decision reached by the main functions.
We need the dynamic-wind to be sure that all the before and after functions are called no matter what
happens during the handling of the main functions.
</p>

<p>We can also use a hook as a normal procecdure, but now the function
lists make it easy to extend an existing function.  
The next example adds to a numerical function the possibility of calling it
with a string:
</p>

<pre class="indented">
&gt; (define h (make-hook '(x 0.0)))
h
&gt; (set! (hook-functions h) ; these are the 'body' functions
        (list (lambda (hook) 
                (set! (hook 'result) (+ (hook 'x) 1.0)))))
(#&lt;lambda (hook)&gt;)
&gt; (h 2.5)
3.5
&gt; (set! ((procedure-environment h) 'init) 
        (list (lambda (hook) ; if x is a string, convert it to a number
                (if (string? (hook 'x)) 
                    (set! (hook 'x) (string-&gt;number (hook 'x)))))))
(#&lt;lambda (hook)&gt;)
&gt; (h "2.5")
3.5
</pre>






<div class="header" id="procedureinfo"><h4>procedure info</h4></div>


<pre class="indented">
(<em class=def id="procedurename">procedure-name</em> proc)
(<em class=def id="proceduresource">procedure-source</em> proc)
(<em class=def id="procedurearity">procedure-arity</em> proc) ; obsolete
(<em class=def id="proceduredocumentation">procedure-documentation</em> proc)
(<em class=def id="proceduresetter">procedure-setter</em> proc)
(procedure-environment proc)

(<em class=def id="arity">arity</em> obj)
(<em class=def id="aritablep">aritable?</em> obj num-args)
</pre>

<p>procedure-source, procedure-arity, procedure-setter, procedure-documentation, and help provide a look into a
Scheme function.
procedure-documentation returns the documentation string associated with a procedure: the initial string in the
function's body. procedure-arity returns a list describing the argument list of a function: <code>'(required-args optional-args rest-arg?)</code>.
procedure-setter returns or sets the set function associated with a procedure (set-car! with car, for example).
procedure-source returns the procedure source (a list). procedure-environment returns
a procedure's environment.  procedure-name returns the procedure's name.
</p>

<pre class="indented">
(define (procedure-arglist f) (cadr (procedure-source f)))
</pre>

<p>In s7 lots of things are applicable, so procedure-arity is too restricted,
and in its main use (checking that a function can be applied to some arguments),
it is very clumsy.
So, s7 has two generic functions:
arity and aritable?.  arity takes any object and returns either #f if it is not applicable,
or a cons containing the minimum and maximum number of arguments acceptable.  If the maximum reported
is a really big number, that means any number of arguments is ok.
aritable? takes two arguments, an object and an integer, and returns #t if the object can be
applied to that many arguments.
</p>

<pre class="indented">
&gt; (define* (add-2 a (b 32)) "add-2 adds its 2 args" (+ a b))
add-2

&gt; (procedure-documentation add-2)
"add-2 adds its 2 args"

&gt; (procedure-arity add-2)
(0 2 #f)

&gt; (procedure-source add-2)
(lambda* (a (b 32)) "add-2 adds its 2 args" (+ a b))
</pre>


<blockquote>

<div class="indented">

<p>procedure-source returns the actual function source &mdash;
more fun than a barrel of monkeys!
If you modify the procedure source directly, it is safest to redefine the procedure
so that everything in s7 knows about the change.  
Here'a an example that adds trace and local variable info for debugging:
</p>

<pre>
(define-bacro (procedure-annotate proc) ; use "bacro" so we can annotate local functions
  (let ((orig (<em class=red>procedure-source</em> proc)))

    (define (proc-walk source)
      (if (pair? source)
	  (if (or (eq? (car source) 'let)     ; if let or let*, show local variables
		  (eq? (car source) 'let*))
	      (if (symbol? (cadr source))
		  ;; (let name vars . body) -&gt; (let name vars print-vars . body)
		  (append 
		   (list (car source)
			 (cadr source)
			 (caddr source)
			 `(format #t "    (let ~A (~{~A~^ ~}) ...)~%" 
                                  ,(cadr source) (environment-&gt;list (current-environment))))
		   (cdddr source))
		  ;; (let(*) vars . body) -&gt; (let vars print-vars . body)
		  (append 
		   (list (car source)
			 (cadr source)
			 `(format #t "    (~A (~{~A~^ ~}) ...)~%" 
                                  ,(car source) (environment-&gt;list (current-environment))))
		   (cddr source)))
	      (cons (proc-walk (car source))
		    (proc-walk (cdr source))))
	  source))

    (let* ((new-body (proc-walk orig))
	   (result (gensym))
	   (new-source 
	    `(lambda ,(cadr orig)
	       (let ((,result #&lt;undefined&gt;))
		 (dynamic-wind
		     (lambda ()       ; upon entry, show procedure name and args
		       (format #t "(~A~{ ~A~})~%" 
                               ',proc 
                               (environment-&gt;list 
                                 (outer-environment 
                                   (outer-environment (current-environment))))))
		     (lambda ()
		       (set! ,result (,new-body ,@(cadr orig)))
		       ,result)
		     (lambda ()       ; at exit, show result
		       (if (eq? ,result #&lt;undefined&gt;)
			   (format #t "  ~A returns early~%")
			   (format #t "  ~A returns ~A~%" ',proc ,result))))))))

      `(set! ,proc (eval ,new-source)))))
			 
&gt; (define (hi a) (let ((b 12)) (+ b a)))
hi
&gt; (procedure-annotate hi)
#&lt;lambda (a)&gt;
&gt; (let ((x 32)) (+ 1 (hi x)))
45
;; printing: 
(hi (a . 32))
    (let ((b . 12)) ...)
  hi returns 44
</pre>

<p>But maybe something less invasive is better. Here's a version of let that prints
its bindings (this is borrowed from "nuntius" at reddit lisp):
</p>

<pre>
(define-macro (print-let bindings . body)
  (let ((temp-symbol (gensym)))
    `(let ,(map (lambda (var/val)
		  `(,(car var/val) 
		    (let ((,temp-symbol ,(cadr var/val))) 
		      (format #t ";~S: ~S -&gt; ~S~%" 
			      ',(car var/val) 
			      ',(cadr var/val) 
			      ,temp-symbol)
		      ,temp-symbol)))
		bindings)
       ,@body)))

;; or simpler:

(define-macro (print-let bindings . body)
  `(let ,bindings 
     (format #t "~{;~A~%~}" (current-environment))
     ,@body))	      
</pre>

</div>


<div class="indented">

<p>Since define* accepts multiple rest arguments, perhaps procedure-arity should return that number,
rather than a boolean.  I haven't run into a case where it matters.  Another odd case: 
<code>(procedure-arity (lambda* (:allow-other-keys) #f))</code>.  How should we indicate
this in procedure-arity?
</p>

<p>In define*, an argument's default value can be a function, so we can store
argument-specific documentation in the documentation string:
</p>
<pre class="indented">
(define (arg-info f n) 
  ((procedure-source f) 1 n 1 0 2)) ; get the documentation string of f's n-th argument

(define* (add-1 (arg ((lambda () "arg should be an integer" 0)))) 
  (+ arg 1))          ; the default value of arg is 0

&gt; (add-1)
1
&gt; (arg-info add-1 0)
"arg should be an integer"
</pre>

<p>This is a lot of boilerplate for a simple notion, 
so I implemented parameter docstrings such as:
<code>(define* (add-1 (arg 0 "arg should be an integer")) (+ arg 1))</code>,
but then decided not to go that way after all.
</p>
</div>


<div class="indented">

<pre>
(define (for-each-subset func args)
  ;; form each subset of args, apply func to the subsets that fit its arity
  (define (subset source dest len)
    (if (null? source)
        (if (<em class=red>aritable?</em> func len)             ; does this subset fit?
	    (apply func dest))
	(begin
	  (subset (cdr source) (cons (car source) dest) (+ len 1))
	  (subset (cdr source) dest len))))
  (subset args () 0))
</pre>
</div>

</blockquote>







<div class="header" id="evalstring"><h4>eval</h4></div>

<p>
<b>eval</b> evaluates its argument, a list representing a piece of code.  It takes an optional
second argument, the environment in which the evaluation should take place.  <b>eval-string</b>
is similar, but its argument is a string.
</p>

<pre class="indented">
&gt; (eval '(+ 1 2))
3
&gt; (eval-string "(+ 1 2)")
3
</pre>


<blockquote>


<div class="indented">

<p>The environment argument is mainly useful in debugging.  A breakpoint can be set, for
example, then any input is evaluated in the environment of the break.  Say we have the
following code in ex.scm:
</p>

<pre>
(define-macro (break)
  `(let ((break-env (<em class=red>current-environment</em>))
	 (prompt (format #f "~%~A &gt; " (if (defined? __func__) __func__ "break"))))
     (call-with-exit
      (lambda (return)
	(do () ()                       ; our debugger's own REPL
	  (display prompt)              ; show where we stopped
	  (let ((str (read-line)))      ; read a line of input, :go -&gt; exit the debugger
	    ;; the nil argument to read-line makes sure that we read C's stdin.  In any normal
	    ;;    program, we'd get the string from a text widget.
	    (if (&gt; (length str) 0)
		(catch #t               ; try to handle typing mistakes etc
		       (lambda ()
			 (let ((val (<em class=red>eval-string</em> str <em class=red>break-env</em>)))
			   (if (eq? val :go)
			       (return))
			   (write val)))
		       (lambda args
			 (format #t "error: ~A" args))))))))))

;; now some random code that has a breakpoint
(define (a-function b)
  (let ((x 32))
    (do ((i 0 (+ i 1)))
	((= i 10))
      (if (= i 3)
	  (<em class=red>break</em>)))
    x))

(a-function 123)
(display "done!") (newline)
</pre>

<p>
Start up a REPL, and:
</p>

<pre class="indented">
&gt; (load "ex.scm")
(a-function "ex.scm" 26) &gt; x    ; here we're in the debugger
32
(a-function "ex.scm" 26) &gt; (+ b i)
126
(a-function "ex.scm" 26) &gt; :go
done!
</pre>
</div>

</blockquote>







<div class="header" id="IO"><h4>IO and other OS functions</h4></div>



<p>Besides files, ports can also represent strings and functions.  The string port functions
are:
</p>

<pre class="indented">
(with-output-to-string thunk)         ; open a string port as current-output-port, call thunk, return string
(with-input-from-string string thunk) ; open string as current-input-port, call thunk
(call-with-output-string proc)        ; open a string port, apply proc to it, return string
(call-with-input-string string proc)  ; open string as current-input-port, apply proc to it
(open-output-string)                  ; open a string output port
(get-output-string port)              ; return output accumulated in the string output port
(open-input-string string)            ; open a string input port reading string
</pre>

<pre class="indented">
&gt; (let ((result #f) 
        (p (<em class=red>open-output-string</em>)))
    (format p "this ~A ~C test ~D" "is" #\a 3)
    (set! result (<em class=red>get-output-string</em> p))
    (close-output-port p)
    result)
"this is a test 3"
</pre>

<p>Other functions:
</p>

<ul>
<li>read-byte and write-byte: binary IO.
<li>read-line: line-at-a-time reads (for write-line, use format or for-each with write-char).
<li>current-error-port, set-current-error-port
</ul>

<p>The variable <em class=def id="vectorprintlength">*vector-print-length*</em> sets
the upper limit on how many vector elements are printed by object-&gt;string and format.
The end-of-file object is #&lt;eof&gt;. 
When running s7 behind a GUI, you often want input to come from and output to go to
arbitrary widgets. The function ports provide a way to redirect IO.  See <a href="#functionportexample">below</a>
for an example.
</p>


<blockquote>

<div class="indented">

<p>
The default IO ports are *stdin*, *stdout*, and *stderr*.
*stderr* is useful if you want to make sure output is flushed out immediately.
The default output port is *stdout* which buffers output until a newline is seen.
In most REPLs, the input port is set up by the REPL, so you need to use
*stdin* if you want to read from the terminal instead:  
</p>

<pre class="indented">
&gt; (read-char)
#&lt;eof&gt;
&gt; (read-char *stdin*)
a          ; here s7 waited for me to type "a" in the terminal
#\a        ; this is the REPL reporting what read-char returned
</pre>

</div>


<div class="indented">

<p>binary-io.scm in the Snd package has functions that read and write integers and floats in
both endian choices in a variety of sizes.  Besides read-byte and write-byte, it uses
integer-decode-float, and the various bitwise operators.
</p>

</div>
</blockquote>

<p>If the compile time switch WITH_SYSTEM_EXTRAS is 1, several additional OS-related and
file-related functions are built-in.  This is work in progress; currently this switch
adds:
</p>

<pre class="indented">
(directory? str)         ; return #t if str is the name of a directory
(file-exists? str)       ; return #t if str names an existing file
(delete-file str)        ; try to delete the file, return 0 is successful, else -1
(getenv var)             ; return the value of an environment variable: (getenv "HOME")
(directory-&gt;list dir)    ; return contents of directory as a list of strings (if HAVE_DIRENT_H)
(system command)         ; execute command
</pre>

<p>But maybe this is not needed; see <a href="#cload">cload.scm</a> below for
a more direct approach.
</p>





<div class="header" id="errors"><h4>error handling</h4></div>

<pre class="indented">
(error tag . info)           ; signal an error of type tag with addition information
(catch tag body err)         ; if error of type tag signalled in body (a thunk), call err with tag and info
(throw tag . info)           ; jump to corresponding catch
</pre>

<p>s7's error handling mimics that of Guile.  An error is signalled
via the error function, and can be trapped and dealt with via <em class=def id="catch">catch</em>.
</p>

<pre class="indented">
&gt; (<em class=red>catch</em> 'wrong-number-of-args
    (lambda ()     ; code protected by the catch
      (abs 1 2))
    (lambda args   ; the error handler
      (apply format #t (cadr args))))
"abs: too many arguments: (1 2)"

&gt; (<em class=red>catch</em> 'division-by-zero
    (lambda () (/ 1.0 0.0))
    (lambda args (string-&gt;number "inf.0")))
inf.0

(define-macro (catch-all . body)
  `(<em class=red>catch</em> #t (lambda () ,@body) (lambda args args)))
</pre>

<p>
catch has 3 arguments: a tag indicating what error to catch (#t = anything),
the code, a thunk, that the catch is protecting, and the function to call
if a matching error occurs during the evaluation of the thunk.  The error handler
takes a rest argument which will hold whatever the error function chooses to pass it.
The error function itself takes at least 2 arguments, the error type, a symbol,
and the error message.  There may also be other arguments describing the error.
The default action, in the absence of any catch, is to treat the message as
a format control string, apply format to it and the other arguments, and
send that info to the current-error-port.
</p>


<blockquote>
<div class="indented">
<p>Normally when reading a file, we have to check for #&lt;eof&gt;, but we can let s7
do that:
</p>

<pre>
(define (copy-file infile outfile)
  (call-with-input-file infile
    (lambda (in)
      (call-with-output-file outfile
	(lambda (out)
	  (<em class=red>catch</em> 'wrong-type-arg   ; s7 raises this error if write-char gets #&lt;eof&gt;
	    (lambda () 
	      (do () ()            ; read/write until #&lt;eof&gt;
		(write-char (read-char in) out)))
	    (lambda err 
	      outfile)))))))
</pre>

<p>catch is not limited to error handling:
</p>

<pre class="indented">
(define (map-with-exit func . args)
  ;; map, but if early exit taken, return the accumulated partial result
  ;;   func takes escape thunk, then args
  (let* ((result ())
	 (escape-tag (gensym))
	 (escape (lambda () (throw escape-tag))))
    (<em class=red>catch</em> escape-tag
      (lambda ()
	(let ((len (apply max (map length args))))
	  (do ((ctr 0 (+ ctr 1)))
	      ((= ctr len) (reverse result))      ; return the full result if no throw
	    (let ((val (apply func escape (map (lambda (x) (x ctr)) args))))
	      (set! result (cons val result))))))
      (lambda args
	(reverse result))))) ; if we catch escape-tag, return the partial result

(define (truncate-if func lst)
  (map-with-exit (lambda (escape x) (if (func x) (escape) x)) lst))

&gt; (truncate-if even? #(1 3 5 -1 4 6 7 8))
(1 3 5 -1)
</pre>

<p>But this is less useful than map (it can't map over a hash-table for example),
and is mostly reimplementing built-in code.  Perhaps s7 should have an extension
of map (and more usefully, for-each) that is patterned after dynamic-wind:
<code>(dynamic-for-each init-func main-func end-func . args)</code> where init-func
is called with one argument, the length of the shortest sequence argument (for-each
and map know this in advance); main-func takes n arguments where n matches
the number of sequences passed; and end-func is called even if a jump out of main-func
occurs (like dynamic-wind in this regard).  In the dynamic-map case, the end-func
takes one argument, the current, possibly partial, result list.  dynamic-for-each
then could easily (but maybe not efficiently) implement generic functions such as -&gt;list, -&gt;vector, and
-&gt;string (converting any sequence into a sequence of some other type).
map-with-exit would be
</p>
<pre class="indented">
(define (map-with-exit func . args) 
  (let ((result ()))
    (call-with-exit
      (lambda (quit)
        (apply dynamic-map #f ; no init-func in this case
               (lambda main-args 
                 (apply func quit main-args)) 
               (lambda (res) 
                 (set! result res))
               args)))
    result))
</pre>
</div>

<div class="indented">
<p>With all the lambda boilerplate, nested catches are hard to read:
</p>
<pre class="indented">
(catch #t
  (lambda ()
    (catch 'division-by-zero
      (lambda ()
	(catch 'wrong-type-arg
	  (lambda () 
	    (abs -1))
	  (lambda args (format #t "got a bad arg~%") -1)))
      (lambda args 0)))
  (lambda args 123))
</pre>

<p>Perhaps we need a macro:
</p>

<pre class="indented">
(define-macro (catch-case clauses . body)
  (let ((base `(lambda () ,@body)))
    (for-each (lambda (clause)
	        (let ((tag (car clause)))
	          (set! base `(lambda () 
			        (catch ',(if (eq? tag 'else) #t tag)
			          ,base 
			          ,@(cdr clause))))))
	      clauses)
    (caddr base)))

;;; the code above becomes:
(catch-case ((wrong-type-arg   (lambda args (format #t "got a bad arg~%") -1))
	     (division-by-zero (lambda args 0))
	     (else             (lambda args 123)))
  (abs -1))
</pre>

<p>This is similar to r7rs scheme's "guard", but I don't want a pointless thunk for the body of the catch.
Along the same lines:
</p>
<pre class="indented">
(define (catch-if test func err)
  (catch #t
    func
    (lambda args
      (if (test (car args))
	  (apply err args)
	  (apply throw args))))) ; if not caught, re-raise the error

(define (catch-member lst func err)
  (catch-if (lambda (tag) (member tag lst)) func err))
</pre>
</div>

</blockquote>

<p>When an error is encountered, and when s7 is interrupted via begin-hook, 
(<em class=def id="errorenvironment">error-environment</em>) returns an environment that contains
additional info about that error:
</p>

<ul>
<li>error-type: the error type or tag, e.g. 'division-by-zero
<li>error-data: the message or information passed by the error function
<li>error-code: the code that s7 thinks triggered the error
<li>error-line: the line number of that code
<li>error-file: the file name of that code
</ul>

<blockquote>


<div class="indented">

<p>To find a variable's value at the point of the error: <code>((error-environment) var)</code>.
To list all the local bindings from the error outward:
</p>

<pre class="indented">
(do ((e (outer-environment (error-environment)) (outer-environment e))) 
    ((eq? e (global-environment))) 
  (format #t "~{~A ~}~%" e))
</pre>

<p>To see the current s7 stack, <code>(stacktrace)</code>.  You'll probably
want to use this in conjunction with *error-hook*.
To evaluate the error handler in the environment of the error:
</p>

<pre class="indented">
(let ((x 1))
  (catch #t
	 (lambda ()
	   (let ((y 2))
	     (error 'oops)))
	 (lambda args
	   (with-environment
	    (augment-environment (error-environment)
	     (cons 'args args))    ; add the error handler args
	    (list args x y)))))    ; we have access to 'y'
</pre>

<p>To limit the maximum size of the stack, set *maximum-stack-size*.
</p>
</div>


</blockquote>


<p>The hook <em class=def id="errorhook">*error-hook*</em> provides a way to specialize error reporting.
Its arguments are named 'type and 'data.
</p>

<pre class="indented">
(set! (hook-functions *error-hook*) 
      (list (lambda (hook) 
              (apply format *stderr* (hook 'data)) 
              (newline *stderr*))))
</pre>

<p>
There is a break macro defined in Snd (snd-xen.c)
which allows you to stop at some point, then evaluate arbitrary expressions in that context.
</p>


<div class="indented">
<p>The s7-built-in catch tags are 'wrong-type-arg, 'syntax-error, 'read-error, 
'out-of-memory, 'wrong-number-of-args, 'format-error, 'out-of-range, 'division-by-zero, 'io-error, and 'bignum-error.  
</p>
</div>



<div class="header" id="autoload"><h4>autoload</h4></div>

<!-- INDEX autoload:autoload -->
<p>
If s7 encounters an unbound variable, it first looks to see if it has any autoload information about it.
This info can be declared via <em class=def>autoload</em>, a function of two arguments, the
symbol that triggers the autoload, and either a filename or a function.  If a filename, s7
loads that file; if a function, it is called with one argument, the current (calling) environment.
</p>

<pre class="indented">
(autoload 'channel-distance "dsp.scm") 
;; now if we subsequently call channel-distance but forget to load "dsp.scm" first,
;;   s7 loads "dsp.scm" itself, and uses its definition of channel-distance.
;;   The C-side equivalent is s7_autoload.

;; here is the cload.scm case, loading j0 from the math library if it is called:
(autoload 'j0
	  (lambda (e)
	    (if (not (provided? 'cload.scm))
		(load "cload.scm"))
	    (c-define '(double j0 (double)) "" "math.h")
	    (augment-environment! e (cons 'j0 j0))))
</pre>

<p>The entity (hash-table or environment probably) that holds the autoload info is named *autoload*.
If after checking autoload, the symbol is still unbound, s7 calls
<em class=def id="unboundvariablehook">*unbound-variable-hook*</em>.
The offending symbol is named 'variable in the hook environment.
If after running *unbound-variable-hook*, the symbol is still unbound,
s7 calls the error handler.
</p>

<p>The autoloader knows about s7 environments used as libraries, so, for example,
you can <code>(autoload 'j0 "libm.scm")</code>, then use j0 in scheme code. The first
time s7 encounters j0, j0 is undefined, so
s7 loads libm.scm.  That load returns the C math library as the environment *libm*.
s7 then automatically looks for j0 in *libm*, and defines it for you.
So the result is the same as if you had defined j0 yourself in C code.
You can use the r7rs library mechanism here, or with-environment, or
whatever you want! (In Snd, libc, libm, libdl, and libgdbm are automatically
tied into s7 via autoload, so if you call, for example, frexp, libm.scm
is loaded, and frexp is exported from the *libm* environment, then the
evaluator carries on, as if frexp had always been defined in s7).
</p>
<br>

<blockquote>
<div class="indented">
<p>There are a lot of thoroughly disreputable ways to take advantage of *unbound-variable-hook*.
Here are two.  In the first, we can't ever remember how to get the error environment information
when we're in the REPL, so we tie that action to the question-mark key.  Whenever '?' is typed
in the listener, the error info is typed out.  That first moment of weakness leads inexorably to the second, 
dalliance with symbol-macros!
</p>

<pre class="indented">
&gt; (set! (hook-functions *unbound-variable-hook*)
      (append (hook-functions *unbound-variable-hook*) ; keep existing funcs like autoload
	      (list 
	       (lambda (hook) 
                 (if (memq (hook 'result) '(#&lt;unspecified&gt; #&lt;undefined&gt;))
	             (let ((sym (hook 'variable)))
		       (if (eq? sym '?)                       ; here '?' is the thing typed
		           (do ((e (outer-environment (error-environment)) (outer-environment e))) 
			       ((eq? e (global-environment)) 
                                (set! (hook 'result) #f))
		             (status-report (format #f "~%~A" (environment-&gt;list e)) -1))
                             ;; status-report is a Snd function that (in this case)
		             ;;   sends the data to the Snd listener.	       
                             )))))))
(#&lt;lambda (hook)&gt;)
&gt; (let ((a "hi") (b 2)) (+ a b)) ; hit an error on purpose
;+ argument 1, "hi", is a string but should be a number
;    (+ a b)
&gt; ?
((a . "hi") (b . 2))   ; ? prints the local variable info at the point of the error

&gt; (set! (hook-functions *unbound-variable-hook*)
    (list (lambda (hook)
            (if (eq? (hook 'variable) 'hiho)
                (set! (hook 'result) (sin (random 1.0))))))) ; hiho -&gt; sins of some number
(&lt;lambda (hook)&gt;)
&gt; hiho
0.46727567824396
&gt; hiho
0.64985453979392
</pre>
</div>

</blockquote>



<div class="header" id="constants"><h4>define-constant, constant?, symbol-access</h4></div>


<p><em class=def id="defineconstant">define-constant</em> defines a constant and 
<em class=def id="constantp">constant?</em> returns #t if its argument
is a constant.  A constant in s7 is really constant: it can't be set or rebound.
</p>

<pre class="indented">
&gt; (define-constant var 32)
var

&gt; (set! var 1)
;set!: can't alter immutable object: var

&gt; (let ((var 1)) var)
;can't bind or set an immutable object: var, line 1
</pre>

<p>This has the possibly surprising side effect that previous uses of the constant name
become constants:
</p>

<pre class="indented">
(define (func a) (let ((cvar (+ a 1))) cvar))
(define-constant cvar 23)
(func 1)
;can't bind or set an immutable object: cvar
</pre>

<p>So, obviously, choose unique names for your constants, or don't use define-constant.
A function can also be a constant. 
</p>

<p>Constants are very similar to things such as keywords (no set, always return itself as its value),
variable trace (informative function upon set or keeping a history of past values), typed variables (restricting a
variable's values or doing automatic conversions upon set), and notification upon set (either in Scheme
or in C; I wanted this many years ago in Snd).  The notification function is especially useful if
you have a Scheme variable and want to reflect any change in its value immediately in C (see <a href="#notify">below</a>).
All of these cases modify
the path between a symbol and its value.  
s7 gives you a handle on that path via <em class=def id="symbolaccess">symbol-access</em>.
<code>(symbol-access symbol)</code> returns that symbol's accessors, and <code>(set! (symbol-access symbol) accessor-list)</code>
changes them.  The symbol-accessor value is a list of three or more items, primarily the set, and bind functions, the second
and third entries in the list respectively.
These two functions take two arguments, the symbol in question
and the value that it is about to be set or bound to.  The variable is set or bound to the value they return.
We could replace define-constant, and add
local constants with:
</p>

<pre class="indented">
(define constant-access 
  (list #f
	(lambda (symbol new-value) 
	  (format #t "can't change constant ~A's value to ~A" symbol new-value)
          'error)
	(lambda (symbol new-value) 
	  (format #t "can't bind constant ~A to a new value, ~A" symbol new-value)
          'error)))

(define-macro (define-constant symbol value)
  `(begin
     (define ,symbol ,value)
     (set! (<em class=red>symbol-access</em> ',symbol) constant-access)
     ',symbol))

(define-macro (let-constant vars . body)
  (let ((varlist (map car vars)))
    `(let ,vars
       ,@(map (lambda (var)
		`(set! (<em class=red>symbol-access</em> ',var) constant-access))
	      varlist)
       ,@body)))
</pre>


<p>In the next example, we restrict the values a variable can take to integers:
</p>

<pre class="indented">
(define-macro (define-integer var value)
  `(begin
     (define ,var ,value)
     (set! (<em class=red>symbol-access</em> ',var) 
	   (list #f
		 (lambda (symbol new-value)
		   (if (real? new-value)
		       (floor new-value) ; or min/max to restrict it to some range etc
                       (begin 
                         (format #t "~A can only take an integer value, not ~S" symbol new-value)
                         'error)))
		 #f))
     ',var))

&gt; (define-integer int 123)
int
&gt; (set! int 321.67)
321
&gt; (set! int (list 1 2))
;int can only take an integer value, not (1 2)
</pre>


<blockquote>
<div class="indented">

<p>Here are trace and untrace.  We save the previous accessors in trace, restore them upon untrace,
and in between, call the previous set accessor, if any, after reporting the set:
</p>

<pre class="indented">
(define (trace var)
  (let* ((cur-access (<em class=red>symbol-access</em> var))
	 (cur-set (and cur-access (cadr cur-access))))
    (set! (<em class=red>symbol-access</em> var)
	  (list (and cur-access (car cur-access))
		(lambda (symbol new-value) 
		  (format #t "~A set to ~A~%" symbol new-value) 
		  (if cur-set 
		      (cur-set symbol new-value)
		      new-value))
		(and cur-access (caddr cur-access))
		cur-access)))) ; save the old version 

(define (untrace var)
  (if (and (symbol-access var)
	   (cdddr (symbol-access var)))
      (set! (symbol-access var) (cadddr (symbol-access var)))))
</pre>
</div>
</blockquote>

<p>The first element of the symbol-accessor list is not used by s7.
It is used for CL-style property lists by symbol-plist and friends in s7test.scm.
I believe symbol-access is similar in spirit to a hooked variable in Ruby, or perhaps a tied variable in Perl (I know nothing about Perl).
</p>




<div class="header" id="miscellanea"><h4>miscellaneous stuff</h4></div>

<p>
<b><em class=def id="loadpath">*load-path*</em></b> is a list of directories to search when loading a file.
<b><em class=def id="loadhook">*load-hook*</em></b> is a hook whose functions are called just before a file is loaded.  
The hook function argument, named 'name, is the filename.
While loading, the port-filename and port-line-number of the current-input-port can tell you
where you are in the file.
</p>

<pre class="indented">
(set! (hook-functions *load-hook*)
       (list (lambda (hook) 
               (format #t "loading ~S...~%" (hook 'name)))))
</pre>

<p>Here's a *load-hook* function that adds the loaded file's directory
to the *load-path* variable so that subsequent loads don't need to specify
the directory:
</p>

<pre class="indented">
(set! (hook-functions <em class=red>*load-hook*</em>)
  (list (lambda (hook)
          (let* ((pos -1)
                 (filename (hook 'name))
	         (len (length filename)))
            (do ((i 0 (+ i 1)))
	        ((= i len))
	      (if (char=? (filename i) #\/)
	          (set! pos i)))
            (if (positive? pos)
	        (let ((directory-name (substring filename 0 pos)))
	          (if (not (member directory-name <em class=red>*load-path*</em>))
		      (set! <em class=red>*load-path*</em> (cons directory-name *load-path*)))))))))
</pre>


<div class="separator"></div>

<p>As in Common Lisp, <b><em class=def id="featureslist">*features*</em></b> is a list describing what is currently loaded into s7.  You can
check it with the <b>provided?</b> function, or add something to it with <b>provide</b>.  In my version of Snd,
at startup *features* is:
</p>

<pre class="indented">
&gt; *features*
(snd-14.1 snd13 snd audio snd-s7 snd-motif gsl alsa xm snd-ladspa clm5 clm 
 sndlib dlopen complex-numbers system-extras @-exponent dfls-exponents s7)
&gt; (provided? 'gmp)
#t
</pre>


<div class="separator"></div>

<p>Multi-line and in-line comments can be enclosed in #| and |#.
<code>(+ #| add |# 1 2)</code>.
</p>

<p>Leaving aside this case and the booleans, #f and #t, you can specify your own handlers for 
tokens that start with "#".  <b><em class=def id="sharpreaders">*#readers*</em></b> is a list of pairs: <code>(char . func)</code>.
"char" refers to the first character after the sharp sign (#). "func" is a function of
one argument, the string that follows the #-sign up to the next delimiter.  "func" is called
when #&lt;char&gt; is encountered.  If it returns something other than #f, the #-expression
is replaced with that value.  Scheme has several predefined #-readers for cases such
as #b1, #\a, #i123, and so on, but you can override these if you like.  If the string
passed in is not the complete #-expression, the function can use read-char or read to get the
rest.  Say we'd like #t&lt;number&gt; to interpret the number in base 12:
</p>

<pre class="indented">
(set! *#readers* (cons (cons #\t (lambda (str) (string-&gt;number (substring str 1) 12))) *#readers*))

&gt; #tb
11
&gt; #t11.3
13.25
</pre>

<p>Or have #c(real imag) be read as a complex number:
</p>

<pre class="indented">
(set! *#readers* (cons (cons #\c (lambda (str) (apply make-rectangular (read)))) *#readers*))

&gt; #c(1 2)
1+2i
</pre>

<div class="indented">
<p>I use *#readers* primarily to implement a way to get the current line number and file name, along
the lines of C's __LINE__ and __FILE__.  port-line-number works if we're reading a file (during load
for example), and (error-environment) has the same information if an error happens.  But during Snd's auto-test
sequence, there are many cases that aren't errors, and the file is no longer being loaded, but
I need to know where something unexpected happened.  So:
</p>

<pre class="indented">
(set! *#readers* 
      (cons (cons #\_ (lambda (str)
			(if (string=? str "__line__")
			    (port-line-number)
			    (if (string=? str "__file__")
			        (port-filename)
			        #f))))
            *#readers*))
</pre>

<p>Here's a reader macro for read-time evaluation:
</p>

<pre class="indented">
(set! *#readers*
  (cons (cons #\. (lambda (str)
		    (if (string=? str ".") (eval (read)) #f)))
	*#readers*))

&gt; '(1 2 #.(* 3 4) 5)
(1 2 12 5)
</pre>

<p>To return no value from a reader, use <code>(values)</code>.
</p>
<pre class="indented">
&gt; (set! *#readers* (cons (cons #\; (lambda (str) (if (string=? str ";") (read)) (values))) *#readers*))
((#\; . #&lt;lambda (str)&gt;))
&gt; (+ 1 #;(* 2 3) 4)
5
</pre>
<p>Here is CL's #+ reader:
</p>
<pre class="indented">
(define (sharp-plus str)
  ;; str here is "+", we assume either a symbol or an expression involving symbols follows
  (let ((e (if (string=? str "+")
		(read)                                ; must be #+(...)
		(string-&gt;symbol (substring str 1))))  ; #+feature
	(expr (read)))  ; this is the expression following #+
    (if (symbol? e)
        (if (provided? e)
	    expr
	    (values))
	(if (pair? e)
	    (begin      ; evaluate the #+(...) expression as in cond-expand
	      (define (traverse tree)
		(if (pair? tree)                                             
		    (cons (traverse (car tree))                             
			  (if (null? (cdr tree)) () (traverse (cdr tree))))
		    (if (memq tree '(and or not)) tree                 
			(and (symbol? tree) (provided? tree)))))
	      (if (eval (traverse e))
		  expr
		  (values)))
	    (error "strange #+ chooser: ~S~%" e)))))
</pre>
<p>See also the <a href="#circularlistreader">#n=</a> reader below.</p>
</div>


<div class="separator"></div>

<p id="makelist">(<b>make-list</b> length (initial-element #f)) returns a list of 'length' elements defaulting to 'initial-element'.
</p>

<p><b>reverse!</b> is an in-place version of the built-in function reverse.  That is, 
it modifies the list passed to it in the process of reversing its contents.
<b>list-set!</b> sets a member of a list.  <b>sort!</b> sorts a list or a vector using the
function passed as its second argument to choose the new ordering.
</p>

<pre class="indented">
&gt; (sort! (list 3 4 8 2 0 1 5 9 7 6) &lt;)
(0 1 2 3 4 5 6 7 8 9)

(define (mix-notelists . notelists)
  ;; assume the second parameter is the begin time in seconds (the first is the instrument name)
  (<em class=red>sort!</em>
   (apply append notelists)
   (lambda (note1 note2)
     (&lt; (cadr note1) (cadr note2)))))

&gt; (mix-notelists '((fm-violin 0 1 440 .1)
		   (fm-violin 1 1 550 .1))
	         '((bird 0 .1 )
		   (bird .2 .1)
		   (bird 1.2 .3)
		   (bird .5 .5)))

((bird 0 0.1) (fm-violin 0 1 440 0.1) (bird 0.2 0.1) (bird 0.5 0.5) (fm-violin 1 1 550 0.1) (bird 1.2 0.3))
</pre>

<p>Despite the "!" in its name, sort! actually copies any list argument passed to it,
but vectors are sorted in place.  
</p>


<div class="separator"></div>

<p>
<b>char-position</b> and <b>string-position</b> search a string for the occurrence of a character,
any of a set of characters, or a string.  They return either #f if none is found, or the position
within the searched string of the first occurrence.  The optional third argument sets where the
search starts in the second argument.
</p>

<pre class="indented">
(<em class=def id="charposition">char-position</em> char-or-string searched-string (start 0))
(<em class=def>string-position</em> substring searched-string (start 0))
</pre>

<p>If char-position's first argument is a string, it is treated as a set of characters, and
char-position looks for the first occurrence of any member of that set.
</p>


<div class="separator"></div>

<p id="keywords">
Keywords exist mainly for define*'s benefit.  The keyword functions are:
<b>keyword?</b>, <b>make-keyword</b>, <b>symbol-&gt;keyword</b>, and <b>keyword-&gt;symbol</b>.
A keyword is a symbol that starts or ends with a colon. The colon
is considered to be a part of the symbol name.  A keyword is a constant that evaluates to itself.
</p>



<div class="separator"></div>

<pre class="indented">
(<em class=def id="symboltable">symbol-table</em>)
(<em class=def id="symboltovalue">symbol-&gt;value</em> sym (env (current-environment)))
(<em class=def id="symboltodynamicvalue">symbol-&gt;dynamic-value</em> sym)
(<em class=def id="definedp">defined?</em> sym (env (current-environment)))
</pre>

<p>
<code>defined?</code> returns #t if the symbol is defined in the environment:
</p>

<pre class="indented">
(define-macro (defvar name value) 
  `(if (not (defined? ',name)) 
       (define ,name ,value)))
</pre>

<p>
<code>symbol-&gt;value</code> returns the value (lexically) bound to the symbol, whereas <code>symbol-&gt;dynamic-value</code>
returns the value dynamically bound to it.  A variable can access both of its values:
</p>
<pre class="indented">
(let ((x 32))
  (define (gx) ; return both bindings of 'x
    (list x (<em class=red>symbol-&gt;value</em> 'x) (<em class=red>symbol-&gt;dynamic-value</em> 'x)))
  (let ((x 100))
    (let ((x 12))
      (values (gx))))) ; this 'values' looks dumb, it is dumb, but see my unconvincing explanantion <a href="#weaselwords">below</a>.
                       ;   briefly: "dynamic binding" in s7 is not "lexically apparent dynamic binding"
&gt; (32 32 12)
</pre>

<p>
<code>symbol-table</code> returns the symbol table, a vector of lists of symbols.
Here we scan the symbol table looking for any function that doesn't have documentation:
</p>

<pre class="indented">
(let ((st (<em class=red>symbol-table</em>)))
  (do ((i 0 (+ i 1))) 
      ((= i (length st)))
    (let ((lst (st i)))
      (for-each 
        (lambda (sym)
          (if (<em class=red>defined?</em> sym)
              (let ((val (<em class=red>symbol-&gt;value</em> sym)))
                (if (and (procedure? val)
                         (string=? "" (procedure-documentation val)))
                    (format #t "~A " sym)))))
        lst)))
  (newline))
</pre>


<div class="indented">

<p>But geez how boring can something be?  Nobody cares about procedure-documentation!
Here's a better example, an automatic software torture tester.
</p>

<pre class="indented">
(let ((constants (list #f #t pi () 1 1.5 3/2 1.5+i)))

  (define (autotest func args args-left)
    (catch #t (lambda () (apply func args)) (lambda any #f))
    (if (&gt; args-left 0)
	(for-each
	 (lambda (c)
	   (autotest func (cons c args) (- args-left 1)))
	 constants)))

  (let ((st (<em class=red>symbol-table</em>)))
    (do ((i 0 (+ i 1))) 
	((= i (length st)))
      (let ((lst (st i)))
	(for-each 
	 (lambda (sym)
	   (if (<em class=red>defined?</em> sym)
	       (let ((val (<em class=red>symbol-&gt;value</em> sym)))
		 (if (procedure? val)
		     (let* ((arity (procedure-arity val))
			    (req (car arity))
			    (opt (cadr arity))
			    (rst (caddr arity)))
		       (if (or (&gt; (+ opt req) 4)
		       	       (member (symbol-&gt;string sym) '("exit" "abort")))
			   (format #t ";skip ~A for now~%" sym) ; no time! no time!
			   (begin
			     (format #t ";whack on ~A...~%" sym)
			     (autotest val () (+ req opt 1 (if rst 1 0))))))))))
	 lst)))))
</pre>

<p>Equally useful, a profiler:
</p>

<pre class="indented">
(define (<em class=def id="profile">profile</em> expression)
  "(profile func) evaluates the function, then reports profiling information. \
The function takes one argument, the environment in which loads and evals should operate."

  (define calls (make-vector 4096 (cons 'unused -1)))
  (define call 0)

  (define (profile-1 n)
    (set! (cdr (calls n)) (+ (cdr (calls n)) 1)))
  
  (define (wrap-all)
    (let ((st (<em class=red>symbol-table</em>))
	  (e (environment)))
      (do ((i 0 (+ i 1))) 
	  ((= i (length st)))
	(let ((lst (st i)))
	  (for-each 
	   (lambda (sym)
	     (if (and (<em class=red>defined?</em> sym)
		      (not (constant? sym)))
		 (let ((val (<em class=red>symbol-&gt;value</em> sym)))
		   (if (procedure? val)
		       (let ((new-val (apply lambda 'args `((profile-1 ,call) (apply ,val args)))))
			 (set! (calls call) (cons sym 0))
			 (set! call (+ call 1))
			 (if (procedure-setter val)
			     (set! (procedure-setter new-val) (procedure-setter val)))
			 (augment-environment! e (cons sym new-val)))))))
	   lst)))
      e))

  (expression (wrap-all))
  (sort! calls (lambda (a b) (&gt; (cdr a) (cdr b))))
  (do ((i 0 (+ i 1)))
      ((= i call))
    (if (&gt; (cdr (calls i)) 0)
	(format #t "~A: ~A~%" (car (calls i)) (cdr (calls i))))))

&gt; (profile (lambda (e) 
             (load "lint.scm" e) 
             (eval '(lint "dsp.scm") e)))
;;; many lines of data print out
</pre>
</div>

<div class="indented" id="weaselwords">
<p>So why, you are asking, the useless 'values' in our dynamic binding example?  The short answer: tail calls.
The long winded one goes something like this.  symbol-&gt;dynamic-value searches the stack to find
the latest binding of its argument.  But because we want to support tail calls, "let" does not
push anything on the stack.  If we call a function as the last thing that happens in that let's body,
and it tries (internally) to access a dynamic binding, the let that launched the function no longer exists; it might already
be garbage collected, and it certainly isn't on the stack. Take our earlier example without the
'values':
</p>

<pre class="indented">
(let ((x 32))
  (define (gx) 
    (symbol-&gt;dynamic-value 'x))
  (let ((x 100))
    (gx)))
</pre>

<p>
This returns 32 because the <code>(x 100)</code> binding no longer exists anywhere when the gx body is evaluated.
So, in s7, the "dynamic binding" of x is the last binding of x that is accessible
to s7.  This may not be the last binding that we can see in the code text, but I don't see that as
an inconsistency. It's not lexical after all. 
Leaving aside this special case, so to speak,
dynamic binding does what you'd expect, even in the context of call/cc.  See s7test.scm for
the MIT-Scheme test of that interaction.
</p>
</div>


<div class="separator"></div>

<p id="s7help"><b>help</b> tries to find information about its argument.
</p>

<pre class="indented">
&gt; (help 'caadar)
"(caadar lst) returns (car (car (cdr (car lst)))): (caadar '((1 (2 3)))) -&gt; 2"
</pre>

<p>If the initial expression in a function body is a string constant, it is assumed to be a documentation string (accessible via help or procedure-documentation):
</p>

<pre class="indented">
(define (add1 a)
  "(add1 a) adds 1 to its argument"
  (+ a 1))

&gt; (help add1)
"(add1 a) adds 1 to its argument"
</pre>


<div class="separator"></div>

<p id="s7gc"><b>gc</b> calls the garbage collector.  <code>(gc #f)</code> turns off the GC, and <code>(gc #t)</code> turns it on.
</p>


<div class="separator"></div>

<pre class="indented">
(<b><em class=def id="morallyequalp">morally-equal?</em></b> x y)
</pre>

<p>
Say we want to check that two different computations came to the same result, and that result might
involve circular structures.  Will equal? be our friend?
</p>

<pre class="indented">
&gt; (equal? 2 2.0)
#f
&gt; (let ((x +nan.0)) (equal? x x))
#f
&gt; (equal? .1 1/10)
#f    
&gt; (= .1 1/10)
#f
&gt; (= 0.0 0+1e-300i)
#f
</pre>

<p>No! We need an equality check that ignores epsilonic differences in real and
complex numbers, and knows that NaNs are equal for all practical purposes.
Leaving aside numbers, 
closed ports are not equal, yet nothing can be done with them.
#() is not equal to #2d().  And two closures are never equal, even if their
arguments, environments, and bodies are equal.
Since there might be circles, it is not easy to write
a replacement for equal? in Scheme.
So, in s7, if one thing is basically the same as
some other thing, they satisfy the function morally-equal?.
</p>

<pre class="indented">
&gt; (morally-equal? 2 2.0)        ; would "equal!?" be a better name?
#t
&gt; (morally-equal? 1/0 1/0)      ; NaN
#t
&gt; (morally-equal? .1 1/10)
#t                              ; floating-point epsilon here is 1.0e-15 or thereabouts
&gt; (morally-equal? 0.0 1e-300)
#t
&gt; (morally-equal? 0.0 1e-14)
#f                              ; its not always #t!
&gt; (morally-equal? (lambda () #f) (lambda () #f))
#t
</pre>

<p>I'd be happy to add *float-epsilon* or some such variable, if anyone needs 
it.  
Also, I can't decide how bignums should interact with morally-equal?.  Currently,
if a bignum is involved, either here or in a hash-table, s7 uses equal?.
</p>


<!--
<p>
<b>define-expansion</b> defines read-time macros, which are just dangerous enough that
I probably shouldn't document them.  It has the same syntax as
define-macro, and the same result except that the macro is
dealt with at read time!  (This means it does not respect attempts to
bind it to something else, which is asking for confusion).
This should be named define-reader-macro.
</p>
-->


<div class="separator"></div>

<blockquote>

<div class="indented">
<p id="s7vsr5rs">Some other differences from r5rs:
</p>

<ul>
<li>no force or delay (see <a href="#r7rs">below</a>).
<li>no syntax-rules or any of its friends.
<li>no scheme-report-environment, null-environment, or interaction-environment (use current-environment).
<li>no transcript-on or transcript-off.
<li>begin returns the value of the last form; it can contain both definitions and other statements.
<li>#&lt;unspecified&gt;, #&lt;eof&gt;, and #&lt;undefined&gt; are first-class objects.
<li>for-each and map accept different length arguments; the operation stops when any argument reaches its end.
<li>for-each and map accept any applicable object as the first argument, and any sequence as a trailing argument.
<li>letrec*, but without conviction.
<li>set! and *-set! return the new value (modulo symbol-access), not #&lt;unspecified&gt;.
<li>port-closed?
<li>current-input-port, current-output-port, and current-error-port have setters
<li>the default IO ports are named *stdin*, *stdout*, and *stderr*.
<li>member and assoc accept an optional third argument, the comparison function (equal? is the default).
<li>case accepts =&gt; much like cond (the function argument is the selector).
<li>if WITH_SYSTEM_EXTRAS is 1, the following are built-in: directory?, file-exists?, delete-file, system, directory-&gt;list, getenv.
<li>s7 is case sensitive.
<li>when and unless (for r7rs), returning the value of the last form.
</ul>

</div>

<!-- null-environment does not fit very well; how to shadow earlier define-constant for example
     one of which is initial-environment; perhaps make a special environment at init time? 
     the code for that is save_null_environment, but it is untested and commented out.

     (define (f1 a) a) (define (f2) (f1 2)) (define (f1 a) (+ a 1)) (f2) returns 3,
     but this is only guaranteed in s7 for closures -- built-in functions may be optimized
     away before a redefinition comes along.
-->

<div class="indented">

<p>Here are some changes I'd make to s7 if I didn't care about compatibility with other Schemes:
</p>

<ul>
<li>remove the exact/inexact distinction including #i and #e
<li>remove #d and #o (who uses octal anymore?)
<li>remove `#(...) support (quasiquoted vector constants)
<li>remove call-with-values and its friends
<li>remove char-ready?
<li>change eof-object? to eof? or end-of-input? or just omit it (you can use eq? #&lt;eof&gt;)
<li>remove the "d", "f", "s", and "l" exponent markers (leaving "e", "E", and "@")
<li>change make-rectangular to make-complex, and remove make-polar.
<li>remove unquote (the name, not the functionality).
<li>remove cond-expand and letrec*.
</ul>

<p>and perhaps:
</p>

<ul>
<li>remove *-ci functions
<li>remove even? and odd?
<li>remove string-length, vector-length, and hash-table-size.
<li>remove list-ref|set!, string-ref|set!, vector-ref|set!, hash-table-ref|set!, set-car!|cdr!, and set-current-output|input|error-port.
<li>change file-exists? to file? (or omit it and assume use of libc.scm &mdash; why reinvent the wheel?).
<li>change with-output-to-* and with-input-from-* to omit the pointless lambda.
<li>remove all the conversion and copy functions like vector-&gt;list and vector-copy (use copy).
<li>add typeq? and perhaps make null? generic.
<li>change string-&gt;symbol to symbol (what to do with symbol-&gt;string in that case?)
<li>let =&gt; be followed by any number of functions, and change its name to "forth".
</ul>

<p>There are several other less-than-ideal names.  Perhaps s7 should use *pi*, *most-negative-fixnum*,
*most-positive-fixnum* (*fixmost*?) so that all the built-in variables and constants have the
same kind of name (or +pi+ to show it is a constant?).  
All the environment function names are bad &mdash; "environment" by itself
is annoying. 
get-output-string should be current-output-string. write-char behaves like display, not write.  symbol-access is not ideal.
</p>

<p>
The name "cond-expand" is bad &mdash; we're not expanding anything, and the macro's point is to make it easy to
operate with the *features* list; perhaps "cond-provided"?  Not only is cond-expand poorly named, but the whole
idea is clumsy &mdash; no-one has ever exclaimed "Let's use cond-expand!" with a happy heart.
I'd say "use #+ and #-", but that's not quite the right thing either.  Why assume that
the *features* list is the only thing of interest at read time?  
Why restrict where a read-time decision can occur?
I'm currently toying with "reader-expand" (similar to cond-expand, but the code choice happens at read-time),
and "reader-cond" (similar again, but the decision is based on a normal evaluation, not something tied to *features*).
In the latter cases, if the macro returns (values), nothing is placed in the output.  See libc.scm for examples.
</p>

<p>
Better ideas are always welcome!
</p>

<p>Here are the built-in s7 variables:
</p>
<ul>
<li>*bignum-precision*
<li>*gc-stats*
<li>*features*
<li>*vector-print-length*
<li>*maximum-stack-size*
<li>*safety*
<li>*load-path*
<li>*autoload*
<li>*#readers*
</ul>

<p>And the built-in constants:
</p>
<ul>
<li>pi
<li>*stdin* *stdout* *stderr*
<li>*stacktrace*
<li>nan.0 -nan.0 inf.0 -inf.0
<li>most-positive-fixnum most-negative-fixnum
<li>*unbound-variable-hook* *load-hook* *error-hook*
</ul>
</div>


<div class="indented">

<p>Schemes vary in their treatment of ().  s7 considers it a constant that evaluates to itself,
so you don't need to quote it.  <code>(eq? () '())</code> is #t.
This is consistent with, for example,
<code>(eq? #f '#f)</code> which is also #t.
The standard says "the empty list is a special object of its own type", so surely either choice is
acceptable in that regard.  One place where the quote matters is in a case statement; the selector is
evaluated but the key is not:
</p>

<pre class="indented">
&gt; (case '() ((()) 2) (else 1))
2
&gt; (case '() (('()) 2) (else 1)) ; (eqv? '() ''()) is #f
1
;;; which parallels #f (or a number such as 2 etc):
&gt; (case '#f ((#f) 2) (else 1))
2
&gt; (case '#f (('#f) 2) (else 1)) ; (eqv? '#f ''#f) is #f
1
</pre>

<p>Similarly, vector constants do not have to be quoted.  A list constant is quoted
to keep it from being evaluated, but
#(1 2 3) is as unproblematic as "123" or 123.
</p>

<!-- there's another sense in which '() is a constant: you can't apply it to anything. ('() 0) -> error
-->
</div>



<div class="indented">

<p>Schemes also vary in handling trailing arguments:
<code>(* 0 "hi")</code> in Guile returns 0, but s7 gives an error.  
<code>(cond (1) (=&gt;))</code> is 1 in both,  and
<code>(or 1 2 . 3)</code> is an
error in Guile, and 1 in s7!
Because it flushes trailing arguments, Guile returns 0 from <code>(* 0 +inf.0)</code>, but I think it should return NaN.
</p>
</div>



<div class="indented">

<p>And a harder one... How should s7 treat this:
<code>(string-set! "hiho" 1 #\z)</code>, or 
<code>(vector-set! #(1 2 3) 1 32)</code>, or
<code>(list-set! '(1 2 3) 1 32)</code>?
Originally, in s7, the first two were errors, and the third was allowed, which doesn't make much sense.
Guile and Common Lisp accept all three, but that leads to weird cases where we can reach
into a function's body:
</p>

<pre class="indented">
&gt; (let ((x (lambda () '(1 2 3)))) (list-set! (x) 1 32) (x))
(1 32 3) ; s7, Guile

&gt; (flet ((x () '(1 2 3))) (setf (nth 1 (x)) 32) (x))
(1 32 3) ; Clisp

&gt; (let ((x (lambda () (list 1 2 3)))) (list-set! (x) 1 32) (x))
(1 2 3)
</pre>

<p>
But it's possible to reach into a function's closure, even when the
closed-over thing is a constant:
</p>

<pre class="indented">
&gt; (flet ((x () '(1 2 3))) (setf (nth 1 (x)) 32) (x))
(1 32 3)

&gt; (let ((xx (let ((x '(1 2 3))) (lambda () x)))) (list-set! (xx) 1 32) (xx))
(1 32 3)

&gt; (let ((xx (let ((x (list 1 2 3))) (lambda () x)))) (list-set! (xx) 1 32) (xx))
(1 32 3)
</pre>

<p>And it's possible to reach into a constant list via list-set! (or set-car! of course):
</p>

<pre class="indented">
&gt; (let* ((x '(1 2)) (y (list x)) (z (car y))) (list-set! z 1 32) (list x y z))
((1 32) ((1 32)) (1 32))
</pre>

<p>
It would be a programmer's nightmare to have to keep track of which piece of a list is
constant, and an implementor's nightmare to copy every list.  set! in all its forms is
used for its side-effects, so why should we try to put a fence around them?
If we flush "immutable constant" because it is a ham-fisted, whack-it-with-a-shovel approach,
the only real problem I can see is symbol-&gt;string.  In CL, this is explicitly an error:
</p>

<pre class="indented">
&gt; (setf (elt (symbol-name 'xyz) 1) #\X)
*** - Attempt to modify a read-only string: "XYZ"
</pre>

<p>And in Guile:
</p>

<pre class="indented">
&gt; (string-set! (symbol-&gt;string 'symbol-&gt;string) 1 #\X)
ERROR: string is read-only: "symbol-&gt;string"
</pre>

<p>So both have a notion of immutable strings.  
I wonder what other Scheme programmers (not implementors!) want in this situation.
Currently, there are no immutable list, string, or vector constants, and
symbol-&gt;string
returns a copy of the string.
One simple way to ensure immutability is to use copy:
</p>

<pre class="indented">
&gt; (let ((x (lambda () (copy "hiho")))) (string-set! (x) 1 #\x) (x))
"hiho"
</pre>

<p>There is one pitfall here.  s7 normally tries to optimize garbage collection by
removing some constants from the heap.  If that constant is a list or a vector, and you later
set some member of it to something that needs GC protection, nobody in the heap points to it, so
it is GC'd.  Here is an example:
</p>

<pre class="indented">
(define (bad-idea)
  (let ((lst '(1 2 3)))              ; or #(1 2 3) and vector-ref|set
    (let ((result (list-ref lst 1)))
     (list-set! lst 1 (* 2.0 16.6))
     (gc)
     result)))
</pre>

<p>Put this is a file, load it into the interpreter, then call <code>(bad-idea)</code> a
few times.  You can turn off the optimization in question by setting the variable <b>*safety*</b>
to 1.  *safety* defaults to 0.  (Also, if *safety* is not 0, sort! is safe from infinite loops,
and some exceedingly rare local method cases are handled more carefully).
</p>
</div>




<div class="indented">

<p id="circle">s7 handles circular lists and vectors and dotted lists with its customary aplomb.  
You can pass them to memq, or print them, for example; you can even evaluate them.  
The print syntax is borrowed from CL:
</p>

<pre class="indented">
&gt; (let ((lst (list 1 2 3))) 
    (set! (cdr (cdr (cdr lst))) lst) 
    lst)
#1=(1 2 3 . #1#)

&gt; (let* ((x (cons 1 2)) 
         (y (cons 3 x))) 
    (list x y))
(#1=(1 . 2) (3 . #1#)) ; shared lists use the same syntax: '((1 . 2) (3 1 . 2)) spelled out
</pre>

<p id="circularlistreader">
But should this syntax be readable as well?  I'm inclined to say no because
then it is part of the language, and it doesn't look like the rest of the language.
(I think it's kind of ugly).  Perhaps we could implement it via *#readers*:
</p>

<pre>
(define circular-list-reader
  (let ((known-vals #f)
	(top-n -1))
    (lambda (str)

      (define (replace-syms lst)
	;; walk through the new list, replacing our special keywords 
        ;;   with the associated locations

	(define (replace-sym tree getter)
	  (if (keyword? (getter tree))
	      (let ((n (string-&gt;number (symbol-&gt;string (keyword-&gt;symbol (getter tree))))))
		(if (integer? n)
		    (let ((lst (assoc n known-vals)))
		      (if lst
			  (set! (getter tree) (cdr lst))
			  (format *stderr* "#~D# is not defined~%" n)))))))

	(define (walk-tree tree)
	  (if (pair? tree)
	      (begin
		(if (pair? (car tree)) (walk-tree (car tree)) (replace-sym tree car))
		(if (pair? (cdr tree)) (walk-tree (cdr tree)) (replace-sym tree cdr))))
	  tree)

	(walk-tree (cdr lst)))

      ;; str is whatever followed the #, first char is a digit
      (let* ((len (length str))
	     (last-char (str (- len 1))))
	(if (memq last-char '(#\= #\#))             ; is it #n= or #n#?
	    (let ((n (string-&gt;number (substring str 0 (- len 1)))))
	      (if (integer? n)
		  (begin
		    (if (not known-vals)            ; save n so we know when we're done
			(begin
			  (set! known-vals ())
			  (set! top-n n))) 

		    (if (char=? last-char #\=)      ; #n=
			(if (char=? (peek-char) #\()
			    (let ((cur-val (assoc n known-vals)))
			      ;; associate the number and the list it points to
			      ;;    if cur-val, perhaps complain? (#n# redefined)
			      (let ((lst (catch #t 
					   (lambda () 
					     (read))
					   (lambda args             ; a read error
					     (set! known-vals #f)   ;   so clear our state
					     (apply throw args))))) ;   and pass the error on up
				(if (not cur-val)
				    (set! known-vals 
					  (cons (set! cur-val (cons n lst)) known-vals))
				    (set! (cdr cur-val) lst)))
			      
			      (if (= n top-n)            ; replace our special keywords
				  (let ((result (replace-syms cur-val)))
				    (set! known-vals #f) ; '#1=(#+gsl #1#) -&gt; '(:1)!
				    result)
				  (cdr cur-val)))
			    #f)                     ; #n=&lt;not a list&gt;?

			;; else it's #n# &mdash; set a marker for now since we may not 
			;;   have its associated value yet.  We use a symbol name that 
                        ;;   string-&gt;number accepts.
			(symbol-&gt;keyword 
                          (symbol (string-append (number-&gt;string n) (string #\null) " ")))))
		  #f))                             ; #n&lt;not an integer&gt;?
	    #f)))))                                ; #n&lt;something else&gt;?

(do ((i 0 (+ i 1)))
    ((= i 10))
  ;; load up all the #n cases
  (set! *#readers* 
    (cons (cons (integer-&gt;char (+ i (char-&gt;integer #\0))) circular-list-reader)
          *#readers*)))

&gt; '#1=(1 2 . #1#)
#1=(1 2 . #1#)
&gt; '#1=(1 #2=(2 . #2#) . #1#)
#2=(1 #1=(2 . #1#) . #2#)
</pre>

<p>And of course, we can treat these as labels:
</p>

<pre class="indented">
(let ((ctr 0)) #1=(begin (format #t "~D " ctr) (set! ctr (+ ctr 1)) (if (&lt; ctr 4) #1# (newline))))
</pre>

<p>which prints "0 1 2 3" and a newline.
</p>

<br>


<p>Length returns +inf.0 if passed a circular list, and returns a negative
number if passed a dotted list.  In the dotted case, the absolute value of the length is the list length not counting
the final cdr.  <code>(define (circular? lst) (infinite? (length lst)))</code>.
Currently map and for-each accept circular list arguments only if some other argument has a
definite length, but:
</p>

<pre class="indented">
(define (map-once f arg)
  (define* (linearize lst (result ()) (sofar ()))
    (if (or (not (pair? lst))
            (memq lst sofar))
        (reverse! result)
        (linearize (cdr lst) 
		   (cons (car lst) result) 
		   (cons lst sofar))))
  (map f (linearize arg)))
</pre>
<br>

<p>Here's an amusing use of circular lists:
</p>

<pre class="indented">
(define (for-each-permutation func vals)
  ;; apply func to every permutation of vals: 
  ;;   (for-each-permutation (lambda args (format #t "~{~A~^ ~}~%" args)) '(1 2 3))
  (define (pinner cur nvals len)
    (if (= len 1)
        (apply func (cons (car nvals) cur))
        (do ((i 0 (+ i 1)))                       ; I suppose a named let would be more Schemish
            ((= i len))
          (let ((start nvals))
            (set! nvals (cdr nvals))
            (let ((cur1 (cons (car nvals) cur)))  ; add (car nvals) to our arg list
              (set! (cdr start) (cdr nvals))      ; splice out that element and 
              (pinner cur1 (cdr start) (- len 1)) ;   pass a smaller circle on down, "wheels within wheels"
              (set! (cdr start) nvals))))))       ; restore original circle
  (let ((len (length vals)))
    (set-cdr! (list-tail vals (- len 1)) vals)    ; make vals into a circle
    (pinner () vals len)
    (set-cdr! (list-tail vals (- len 1)) ())))    ; restore its original shape
</pre>
</div>



<div class="indented">

<p>s7 and Snd use "*" in a variable name, *features* for example, to indicate
that the variable is predefined.  It may occur unprotected in a macro, for
example.  The "*" doesn't mean that the variable is special in the CL sense of dynamic scope,
but some clear marker is needed for a global variable so that the programmer
doesn't accidentally step on it.  
</p>

<p>Although a variable name's first character is more restricted, currently
only #\null, #\newline, #\tab, #\space, #\), #\(, #\", and #\; can't
occur within the name.  I did not originally include double-quote in this set, so wild stuff like
<code>(let ((nam""e 1)) nam""e)</code>
would work, but that means that <code>'(1 ."hi")</code> is parsed as a 1 and the
symbol <code>."hi"</code>, and <code>(string-set! x"hi")</code> is an error.
The first character should not be #\#, #\', #\`, #\,, #\:, or any of those mentioned above,
and some characters can't occur by themselves.  For example, "." is not a legal variable
name, but ".." is. 
These weird symbols have to be printed sometimes:
</p>

<pre class="indented">
&gt; (list 1 (string-&gt;symbol (string #\; #\" #\\)) 2)
(1 ;"\ 2)            <!-- " -->
&gt; (list 1 (string-&gt;symbol (string #\.)) 2)
(1 . 2)
</pre>

<p>which is a mess.  Guile prints the first as <code>(1 #{\;\"\\}# 2)</code>.
In CL and some Schemes:
</p>

<pre class="indented">
[1]&gt; (list 1 (intern (coerce (list #\; #\" #\\) 'string)) 2) ; thanks to Rob Warnock
(1 |;"\\| 2)        <!-- " -->
[2]&gt; (equalp 'A '|A|) ; in CL case matters here
T
</pre>

<p>This is clean, and has the weight of tradition behind it, but 
I think I'll use "symbol" instead:
</p>

<pre class="indented">
&gt; (list 1 (string-&gt;symbol (string #\; #\" #\\)) 2)
(1 (symbol ";\"\\") 2)       <!-- " -->
</pre>

<p>
This output is readable, and does not eat up perfectly good
characters like vertical bar, but it means we can't easily use
variable names like "| e t c |".  We could allow a name to
contain any characters if it starts and ends with "|",
but then one vertical bar is trouble.  
</p>

<p>
These symbols are not just an optimization of string comparison:
</p>

<pre class="indented">
(define-macro (hi a) 
  (let ((funny-name (string-&gt;symbol (string #\;))))
    `(let ((,funny-name ,a)) (+ 1 ,funny-name))))

&gt; (hi 2)
3
&gt; (macroexpand (hi 2))
(let ((; 2)) (+ 1 ;))    ; for a good time, try (string #\") 

(define-macro (hi a) 
  (let ((funny-name (string-&gt;symbol "| e t c |")))
    `(let ((,funny-name ,a)) (+ 1 ,funny-name))))
&gt; (hi 2)
3
&gt; (macroexpand (hi 2))
(let ((| e t c | 2)) (+ 1 | e t c |))

&gt; (let ((funny-name (string-&gt;symbol "| e t c |"))) ; now use it as a keyword arg to a function
    (apply define* `((func (,funny-name 32)) (+ ,funny-name 1)))
    ;; (procedure-source func) is (lambda* ((| e t c | 32)) (+ | e t c | 1))
    (apply func (list (symbol-&gt;keyword funny-name) 2)))
3
</pre>

<p>I hope that makes you as happy as it makes me!
</p>
</div>




<div class="indented">

<p id="legolambda">The built-in syntactic forms, such as "begin", are almost first-class citizens.
</p>

<pre class="indented">
&gt; (let ((progn begin)) 
    (progn 
      (define x 1) 
      (set! x 3) 
      (+ x 4)))
7
&gt; (let ((function lambda)) 
    ((function (a b) (list a b)) 3 4))
(3 4)
&gt; (apply begin '((define x 3) (+ x 2)))
5
&gt; ((lambda (n) (apply n '(((x 1)) (+ x 2)))) let)
3

(define-macro (symbol-set! var val) ; like CL's set
  `(apply set! ,var ',val ()))      ; trailing nil is just to make apply happy &mdash; apply*?

(define-macro (progv vars vals . body)
 `(apply (apply lambda ,vars ',body) ,vals))

&gt; (let ((s '(one two)) (v '(1 2))) (progv s v (+ one two)))
3
</pre>

<p>We can snap together program fragments ("look Ma, no macros!"):
</p>

<pre class="indented">
(let* ((x 3) 
       (arg '(x)) 
       (body `((+ ,x x 1)))) 
  ((apply lambda arg body) 12)) ; "legolambda"?

(let ()
  (define (hi a) (+ a x))
  ((apply let '((x 32)) (list (procedure-source hi))) 12)) ; one function, many closures?

(let ((ctr -1))  ; (enum zero one two) but without using a macro
  (apply begin 
    (map (lambda (symbol) 
           (set! ctr (+ ctr 1)) 
           (list 'define symbol ctr)) ; e.g. '(define zero 0) 
         '(zero one two)))
  (+ zero one two))
</pre>

<p>If you apply define or define-macro, the returned value is a symbol, so to apply the
new function or macro, you need to use either eval or symbol-&gt;value:
</p>

<pre class="indented">
&gt; ((symbol-&gt;value (apply define-macro '((m a) `(+ 1 ,a)))) 3)
4
&gt; ((symbol-&gt;value (apply define '((hi a) (+ a 1)))) 3)
4
</pre>

<p>This gives us a way to make anonymous macros, just as lambda returns an anonymous function:
</p>

<pre class="indented">
(define-macro (mu args . body)
  `(symbol-&gt;value (apply define-macro '((,(gensym) ,@args) ,@body))))

&gt; ((mu (a) `(+ 1 ,a)) 3)
4
&gt; (define-macro (glambda args) ; returns an anonymous macro that will return a function given a body
    `(symbol-&gt;value (define-macro (,(gensym) . body) 
                      `(lambda ,',args ,@body))))
glambda
&gt; (let ((gf (glambda (a b))))  ; gf is now ready for any body that involves arguments 'a and 'b
    ((gf (+ a b)) 1 2))        ; apply (lambda (a b) (+ a b)) to '(1 2)
3
</pre>

<p>Or another enum (for-each with a macro as its first argument might be called "transparent-for-each"):
</p>

<pre class="indented">
&gt; (define-macro (enum . args)
    `(for-each (let ((ctr -1))
                 (symbol-&gt;value     ; perhaps define-macro and friends should return the value
                   (define-macro (m a) ;   I think they return the symbol for the REPL's benefit(?)
                     (set! ctr (+ ctr 1)) 
                     `(apply define ',a ,ctr ()))))
               ',args))
enum
&gt; (enum a b c)
#&lt;unspecified&gt;
&gt; b
1
</pre>


<p>
Currently, you can't set! a built-in syntactic keyword to some new value:
<code>(set! if 3)</code>.
I hope this kind of thing is not actually very useful, but let me
know if you need it.  The issue is purely one of speed.
</p>

<p>Speaking of speed... It is widely believed
that a Scheme with first class everything can't hope to compete with any
"real" Scheme.  Humph I say.  Take this little example (which is not 
so misleading that I feel guilty about it):
</p>
<pre class="indented">
(define (do-loop n)
  (do ((i 0 (+ i 1)))
      ((= i n))
    (if (zero? (modulo i 1000))
	(display ".")))
  (newline))

(for-each
 (lambda (n) (do-loop n))
 (list 1000 1000000 10000000))
</pre>

<p>In s7, that takes 0.24 seconds on my home machine.  In tinyScheme, from
whence we sprang, it takes 85 seconds.  In the chicken interpreter, 5.3
seconds, and after compilation (using -O2) of the chicken compiler output,
0.75 seconds.  So, s7 is comparable to chicken in speed, even though chicken
is compiling to C. I think Guile 2.0.9 takes about 1 second.
The equivalent in CL:
clisp interpreted 9.3 seconds, compiled 0.85 seconds; sbcl 0.21 seconds.
</p>
</div>




<div class="indented">

<p>In s7, there is only one kind of begin statement,
and it can contain both definitions and expressions.  These are evaluated in the order
in which they occur, and in the environment at the point of the evaluation.  I think
of it as being a little REPL.  begin does not introduce a new frame in
the current environment, so defines happen in the enclosing environment.
</p>


<div class="indented">

<p id="r7rs">The r7rs compatibility code is in r7rs.scm. I used to include it here, but
as r7rs grew, this section got too large.  In general, all the conversion routines in
r7rs are handled in s7 via generic functions, records are classes, bytevectors are
strings, and so on. 
</p>

</div>




<div class="indented">

<p>s7 originally had multithreading support, but I removed it in August, 2011.
It turned out to be less useful than I hoped,
mainly because s7 threads shared the heap and therefore had to coordinate
all cell allocations.  It was faster and simpler to use multiple
processes each running a separate s7 interpreter, rather than one s7
running multiple s7 threads.  In CLM, there was also contention for access
to the output stream.  In GUI-related situations, as discussed at length below,
threads were not useful mainly because the GUI toolkits are not thread safe,
so we use begin_hook now instead.
Last but not least, the effort to make the non-threaded
s7 faster messed up parts of the threaded version.  Rather than
waste a lot of time fixing this, I chose to flush multithreading.
</p>
</div>



<div class="indented">

<p>"Life", a poem.
</p>

<pre class="indented">
(+(*(+))(*)(+(+)(+)(*)))
(((((lambda () (lambda () (lambda () (lambda () 1))))))))
(+ (((lambda () values)) 1 2 3))
(map apply (list map) (list map) (list (list *)) '((((1 2)) ((3 4 5)))))
(do ((do do do)) (do do do))
(*(*)(*) (+)(+) 1)
</pre>
</div>
</blockquote>
<br><br>



<div class="topheader" id="FFIexamples">FFI examples</div>

<p>s7 exists only to serve as an extension of some other application, so
it is primarily a foreign function interface.  s7.h has lots of comments about the individual
functions.  Here I'll collect some complete examples.  s7.c depends on the following
compile-time flags:
</p>

<pre class="indented">
SIZEOF_VOID_P                  8 (default) or 4.
WITH_GMP                       1 if you want multiprecision arithmetic (requires gmp, mpfr, and mpc, default is 0)
HAVE_COMPLEX_NUMBERS           1 if your compiler supports complex numbers
HAVE_COMPLEX_TRIG              1 if your math library has complex versions of the trig functions
WITH_AT_SIGN_AS_EXPONENT       1 if you want "@" to mark exponents (default is 1)
WITH_EXTRA_EXPONENT_MARKERS    1 if you want "d", "f", "l", and "s" in addition to "e" as exponent markers (default is 1)
                                   if someone defends these exponent markers, ask him to read 1l11+11l1i
WITH_SYSTEM_EXTRAS             1 if you want some additional OS-related functions built-in (default is 0)
S7_DISABLE_DEPRECATED          1 if you want to make sure you're not using any deprecated s7 stuff (default is 0)
WITH_MAIN                      1 if you want s7.c to include a main program section that implements a REPL.
</pre>

<p>See the comment at the start of s7.c for more information about these switches.
s7.h defines the two main number types: s7_Int and s7_Double.
The examples that follow show:
</p>

<ul>
<li><a href="#repl">read-eval-print loop (and emacs)</a>
<li><a href="#defun">define a function with arguments and a returned value, and define a variable </a>
<li><a href="#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
<li><a href="#juce">C++ and Juce</a>
<li><a href="#sndlib">load sndlib using the Xen functions and macros</a>
<li><a href="#pwstype">add a new Scheme type and a procedure with a setter</a>
<li><a href="#functionportexample">redirect display output to a C procedure</a>
<li><a href="#extendop">extend a built-in operator ("+" in this case)</a>
<li><a href="#definestar1">C-side define* (s7_define_function_star)</a>
<li><a href="#definemacro1">C-side define-macro (s7_define_macro)</a>
<li><a href="#definegeneric">define a generic function in C</a>
<li><a href="#signal">signal handling (C-C to break out of an infinite loop)</a>
<li><a href="#vector">direct multidimensional vector element access</a>
<li><a href="#notify">notification in C that a Scheme variable has been set!</a>
<li><a href="#namespace">Load C defined stuff into a separate namespace</a>
<li><a href="#Cerrors">Error handling in C</a>
<li><a href="#closure">Closure defined in C</a>
<li><a href="#testhook">Hooks in C and Scheme</a>
<li><a href="#dload">Load a C module dynamically</a>
<li><a href="#gmpex">gmp and friends</a>
<li><a href="#gtkrepl">Gtk-based REPL</a>
<li><a href="#gtkschemerepl">Gtk/Scheme-based REPL</a>
<li><a href="#replrescue">begin_hook to the rescue!</a>
<li><a href="#glistener">glistener.c</a>
<li><a href="#gdb">gdb</a>
</ul>





<div class="header" id="repl"><h4>A simple listener</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include "s7.h"

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = <em class=red>s7_init</em>();                 /* initialize the interpreter */
  while (1)                       /* fire up a read-eval-print loop */
    {
      fprintf(stdout, "\n&gt; ");    /* prompt for input */
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                         /* evaluate the input and print the result */
	  sprintf(response, "(write %s)", buffer);
	  <em class=red>s7_eval_c_string</em>(s7, response); 
	}
    }
}

/* make mus-config.h (it can be empty), then
 *
 *   gcc -c s7.c -I.
 *   gcc -o repl repl.c s7.o -lm -I. -ldl
 *
 * run it:
 *
 *    repl
 *    &gt; (+ 1 2)
 *    3
 *    &gt; (define (add1 x) (+ 1 x))
 *    add1
 *    &gt; (add1 2)
 *    3
 *    &gt; (exit)
 *
 * for long-term happiness in linux use:
 *   gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I. -ldl
 * freebsd:
 *   gcc -o repl repl.c s7.o -Wl,-export-dynamic -lm -I.
 * osx:
 *   gcc -o repl repl.c s7.o -lm -I.
 */
</pre>
</div>


<p>Since this reads stdin and writes stdout, it can be run as a Scheme subjob of emacs.
One (inconvenient) way to do this is to set the emacs variable scheme-program-name to
the name of the exectuable created above ("doc7"), then call the emacs function run-scheme:
M-x eval-expression in emacs, followed by (setq scheme-program-name "doc7"), then
M-x run-scheme, and you're talking to s7 in emacs.  Of course, this connection can be
customized indefinitely.  See, for example, snd-inf.el in the Snd package.
</p>

<p>To read stdin while working in a GUI-based program is trickier.  In glib/gtk, you can use
something like this:
</p>

<blockquote>
<div class="indented">
<pre>
static gboolean read_stdin(GIOChannel *source, GIOCondition condition, gpointer data)
{
  /* here read from g_io_channel_unix_get_fd(source) and call s7_eval_string */
  return(true);
}

/* ... during initialization ... */

GIOChannel *channel;
channel = g_io_channel_unix_new(STDIN_FILENO);  /* watch stdin */
stdin_id = g_io_add_watch_full(channel,         /* and call read_stdin above if input is noticed */
			       G_PRIORITY_DEFAULT, 
			       (GIOCondition)(G_IO_IN | G_IO_HUP | G_IO_ERR), 
			       <em class=red>read_stdin</em>, NULL, NULL);
g_io_channel_unref(channel);
</pre></div>
</blockquote>

<p>Here's a version that uses libtecla for the line editor:
</p>

<blockquote>
<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;libtecla.h&gt;
#include "s7.h"

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char *buffer;
  char response[1024];
  GetLine *gl;            /* The tecla line editor */

  gl = new_GetLine(500, 5000);
  s7 = s7_init();  

  while (1) 
    {
      buffer = gl_get_line(gl, "&gt; ", NULL, 0);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	  fprintf(stdout, "\n");
	}
    }
  gl = del_GetLine(gl);
}

/* 
 *   gcc -c s7.c -I. -O2 -g3
 *   gcc -o ex1 ex1.c s7.o -lm -I. -ltecla -ldl
 */
</pre></div>
</blockquote>

<p>A repl that uses readline instead is built into s7.  Include the compiler flag -DWITH_MAIN:
</p>

<pre class="indented">
in Linux: gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -lreadline -lncurses -lrt -ldl -lm -Wl,-export-dynamic
in *BSD:  gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -lreadline -lncurses -lm -Wl,-export-dynamic
in OSX:   gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -lreadline -lncurses -lm
</pre>

<p>If you prefer C++, here's a C++ version of the listener, extracted from Rick Taube's
Common Music package:
</p>

<blockquote>
<div class="indented">
<pre>
#include &lt;iostream&gt;
#include "s7.h"

static s7_pointer main_quit(s7_scheme *sc, s7_pointer args);
static bool is_balanced(std::string str);
static bool is_not_white(std::string str);

int main(int argc, const char* argv[])
{
  s7_scheme* s7 = s7_init();
  s7_pointer val;
  std::string str;

  try 
    {
      while (std::cin)
	{
	  std::cout &lt;&lt; "\ns7&gt; ";
	  str = "";
	  while (true)
	    {
	      std::string lin;
	      std::getline(std::cin, lin);
	      str = str + lin + "\n";
	      if (is_balanced(str))
		break;
	    }
	  if (is_not_white(str))
	    {
	      val = s7_eval_c_string(s7, str.c_str());
	      std::cout &lt;&lt; s7_object_to_c_string(s7, val);
	    }
	}
    }
  catch(...)
    {
    }
  std::cout &lt;&lt; "Bye!\n";
  return 0;
}

static s7_pointer main_quit(s7_scheme *sc, s7_pointer args)
{
  throw 0;
  return(s7_nil(sc));
}

static bool is_balanced(std::string str)
{
  int parens = 0;
  int quotes = 0;
  unsigned i = 0;
  while (i &lt; str.size())
    {
      if (str[i] == ';')
	{
	  for (i = i + 1; i &lt; str.size(); i++)
	    {
	      if (str[i] == '\n')
		break;
	    }
	}
      else if (str[i] == '"')
	{
	  if (i == 0 || str[i - 1] != '\\')
	    {
	      quotes = 1;
	      for (i = i + 1; i &lt; str.size(); i++)
		{
		  if (str[i] == '"' &amp;&amp; str[i - 1] != '\\')
		    {
		      quotes = 0;
		      break;
		    }
		}
	      if (quotes)
		return false;
	    }
	}
      else if (str[i] == '(')
	parens++;
      else if (str[i] == ')')
	parens--;
      i++;
    }
  return (parens == 0) &amp;&amp; (quotes == 0);
}

static bool is_not_white(std::string str)
{
  for (unsigned i = 0; (i &lt; str.size() &amp;&amp; str[i] != ';'); i++)
    if (str[i] != ' ' && str[i] != '\n' &amp;&amp; str[i] != '\t')
      return true;
  return false;
}

/* g++ -I. -c repl.cpp
 * g++ -o repl repl.o s7.o -ldl
 */
</pre></div>
</blockquote>




<div class="header" id="defun"><h4>Define a function with arguments and a returned value, and a variable</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer add1(s7_scheme *sc, s7_pointer args)
{
  /* all added functions have this form, args is a list, 
   *    s7_car(args) is the first arg, etc 
   */
  if (<em class=red>s7_is_integer</em>(s7_car(args)))
    return(<em class=red>s7_make_integer</em>(sc, 1 + <em class=red>s7_integer</em>(s7_car(args))));
  return(s7_wrong_type_arg_error(sc, "add1", 1, s7_car(args), "an integer"));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();
  
  s7_define_function(s7, "add1", add1, 1, 0, false, "(add1 int) adds 1 to int");
                                      /* add the function "add1" to the interpreter.
                                       *   1, 0, false -&gt; one required arg,
				       *                  no optional args,
				       *                  no "rest" arg
				       */
 <em class=red>s7_define_variable</em>(s7, "my-pi", <em class=red>s7_make_real</em>(s7, 3.14159265));

  while (1)                           /* fire up a "repl" */
    {
      fprintf(stdout, "\n&gt; ");        /* prompt for input */
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response); /* evaluate input and write the result */
	}
    }
}

/*    doc7
 *    &gt; my-pi
 *    3.14159265
 *    &gt; (+ 1 (add1 1))
 *    3
 *    &gt; (exit)
 */
</pre></div>




<div class="header" id="defvar"><h4>Call a Scheme-defined function from C, and get/set Scheme variable values in C</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

int main(int argc, char **argv)
{
  s7_scheme *s7;
  s7 = s7_init();

  s7_define_variable(s7, "an-integer", s7_make_integer(s7, 1));
  s7_eval_c_string(s7, "(define (add1 a) (+ a 1))");
  
  fprintf(stderr, "an-integer: %d\n", 
	  s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));

  <em class=red>s7_symbol_set_value</em>(s7, <em class=red>s7_make_symbol</em>(s7, "an-integer"), s7_make_integer(s7, 32));

  fprintf(stderr, "now an-integer: %d\n", 
	  s7_integer(<em class=red>s7_name_to_value</em>(s7, "an-integer")));

  fprintf(stderr, "(add1 2): %d\n", 
	  s7_integer(<em class=red>s7_call</em>(s7, 
			     s7_name_to_value(s7, "add1"), 
			     s7_cons(s7, s7_make_integer(s7, 2), s7_nil(s7)))));
}

/*
 *    doc7
 *    an-integer: 1
 *    now an-integer: 32
 *    (add1 2): 3
 */
</pre></div>





<div class="header" id="juce"><h4>C++ and Juce, from Rick Taube</h4></div>


<div class="indented">
<pre>
int main(int argc, const char* argv[]) 
{ 
  initialiseJuce_NonGUI(); 

  s7_scheme *s7 = s7_init(); 
  if (!s7) 
    { 
      std::cout &lt;&lt;  "Can't start S7!\n"; 
      return -1; 
    } 

  s7_pointer val; 
  std::string str; 
  while (true) 
    { 
      std::cout &lt;&lt; "\ns7&gt; "; 
      std::getline(std::cin, str); 
      val = s7_eval_c_string(s7, str.c_str()); 
      std::cout &lt;&lt; s7_object_to_c_string(s7, val); 
    } 

  free(s7); 
  std::cout &lt;&lt; "Bye!\n"; 
  return 0; 
} 
</pre></div>





<div class="header" id="sndlib"><h4>Load sndlib into an s7 repl</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;unistd.h&gt;

/* assume we've configured and built sndlib, so it has created a mus-config.h file.
 * also assume we've built s7 with WITH_SYSTEM_EXTRAS set, so we have file-exists? and delete-file
 */

#include "mus-config.h"
#include "s7.h"
#include "xen.h"
#include "clm.h"
#include "clm2xen.h"

/* we need to redirect clm's mus_error calls to s7_error */

static void mus_error_to_s7(int type, char *msg)
{
  s7_error(s7,                               /* s7 is declared in xen.h, defined in xen.c */
	   s7_make_symbol(s7, "mus-error"),
	   s7_cons(s7, s7_make_string(s7, msg), s7_nil(s7)));
}

int main(int argc, char **argv)
{
  char buffer[512];
  char response[1024];

  s7 = s7_init();                     /* initialize the interpreter */
  s7_xen_initialize(s7);              /* initialize the xen stuff (hooks and the xen s7 FFI used by sndlib) */
  Init_sndlib();                      /* initialize sndlib with all the functions linked into s7 */  

  mus_error_set_handler(mus_error_to_s7); /* catch low-level errors and pass them to s7-error */

  while (1)                           /* fire up a "repl" */
    {
      fprintf(stdout, "\n&gt; ");        /* prompt for input */
      fgets(buffer, 512, stdin);

      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response); /* evaluate input and write the result */
	}
    }
}

/* gcc -o doc7 doc7.c -lm -I. /usr/local/lib/libsndlib.a -lasound -ldl
 *
 *   (load "sndlib-ws.scm")
 *   (with-sound () (outa 10 .1))
 *   (load "v.scm")
 *   (with-sound () (fm-violin 0 .1 440 .1))
 *
 * you might also need -lgsl -lgslcblas
 */
</pre></div>





<div class="header" id="pwstype"><h4>Add a new Scheme type and a procedure with a setter</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

/* define *listener-prompt* in scheme, add two accessors for C get/set */

static const char *listener_prompt(s7_scheme *sc)
{
  return(s7_string(s7_name_to_value(sc, "*listener-prompt*")));
}

static void set_listener_prompt(s7_scheme *sc, const char *new_prompt)
{
  s7_symbol_set_value(sc, s7_make_symbol(sc, "*listener-prompt*"), s7_make_string(sc, new_prompt));
}

/* now add a new type, a struct named "dax" with two fields, a real "x" and a list "data" */
/*   since the data field is an s7 object, we'll need to mark it to protect it from the GC */

typedef struct {
  s7_Double x;
  s7_pointer data;
} dax;

static char *print_dax(s7_scheme *sc, void *val)
{
  char *data_str, *str;
  int data_str_len;
  dax *o = (dax *)val;
  data_str = s7_object_to_c_string(sc, o-&gt;data);
  data_str_len = strlen(data_str);
  str = (char *)calloc(data_str_len + 32, sizeof(char));
  snprintf(str, data_str_len + 32, "#&lt;dax %.3f %s&gt;", o-&gt;x, data_str);
  free(data_str);
  return(str);
}

static void free_dax(void *val)
{
  if (val) free(val);
}

static bool equal_dax(void *val1, void *val2)
{
  return(val1 == val2);
}

static void mark_dax(void *val)
{
  dax *o = (dax *)val;
  if (o) s7_mark_object(o-&gt;data);
}

static int dax_type_tag = 0;

static s7_pointer make_dax(s7_scheme *sc, s7_pointer args)
{
  dax *o;
  o = (dax *)malloc(sizeof(dax));
  o-&gt;x = s7_real(s7_car(args));
  if (s7_cdr(args) != s7_nil(sc))
    o-&gt;data = s7_car(s7_cdr(args));
  else o-&gt;data = s7_nil(sc);
  return(<em class=red>s7_make_object</em>(sc, dax_type_tag, (void *)o));
}

static s7_pointer is_dax(s7_scheme *sc, s7_pointer args)
{
  return(s7_make_boolean(sc, 
			 <em class=red>s7_is_object</em>(s7_car(args)) &amp;&amp;
			 <em class=red>s7_object_type</em>(s7_car(args)) == dax_type_tag));
}

static s7_pointer dax_x(s7_scheme *sc, s7_pointer args)
{
  dax *o;
  o = (dax *)<em class=red>s7_object_value</em>(s7_car(args));
  return(s7_make_real(sc, o-&gt;x));
}

static s7_pointer set_dax_x(s7_scheme *sc, s7_pointer args)
{
  dax *o;
  o = (dax *)s7_object_value(s7_car(args));
  o-&gt;x = s7_real(s7_car(s7_cdr(args)));
  return(s7_car(s7_cdr(args)));
}

static s7_pointer dax_data(s7_scheme *sc, s7_pointer args)
{
  dax *o;
  o = (dax *)s7_object_value(s7_car(args));
  return(o-&gt;data);
}

static s7_pointer set_dax_data(s7_scheme *sc, s7_pointer args)
{
  dax *o;
  o = (dax *)s7_object_value(s7_car(args));
  o-&gt;data = s7_car(s7_cdr(args));
  return(o-&gt;data);
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();
  
  s7_define_variable(s7, "*listener-prompt*", s7_make_string(s7, "&gt;"));

  dax_type_tag = <em class=red>s7_new_type</em>("dax", print_dax, free_dax, equal_dax, mark_dax, NULL, NULL);
  s7_define_function(s7, "make-dax", make_dax, 2, 0, false, "(make-dax x data) makes a new dax");
  s7_define_function(s7, "dax?", is_dax, 1, 0, false, "(dax? anything) returns #t if its argument is a dax object");

  s7_define_variable(s7, "dax-x", 
                     <em class=red>s7_make_procedure_with_setter</em>(s7, "dax-x", dax_x, 1, 0, set_dax_x, 2, 0, "dax x field"));

  s7_define_variable(s7, "dax-data", 
                     <em class=red>s7_make_procedure_with_setter</em>(s7, "dax-data", dax_data, 1, 0, set_dax_data, 2, 0, "dax data field"));

  while (1)
    {
      fprintf(stdout, "\n%s ", listener_prompt(s7));
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response); /* evaluate input and write the result */
	}
    }
}

/*
 *    &gt; *listener-prompt*
 *    "&gt;"
 *    &gt; (set! *listener-prompt* ":")
 *    ":"
 *    : (define obj (make-dax 1.0 (list 1 2 3)))
 *    obj
 *    : obj
 *    #&lt;dax 1.000 (1 2 3)&gt;
 *    : (dax-x obj)
 *    1.0
 *    : (dax-data obj)
 *    (1 2 3)
 *    : (set! (dax-x obj) 123.0)
 *    123.0
 *    : obj
 *    #&lt;dax 123.000 (1 2 3)&gt;
 *    : (dax? obj)
 *    #t
 *    : (exit)
 */
</pre></div>





<div class="header" id="functionportexample"><h4>Redirect output (and input) to a C procedure</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static void my_print(s7_scheme *sc, unsigned char c, s7_pointer port)
{
  fprintf(stderr, "[%c] ", c);
}

static s7_pointer my_read(s7_scheme *sc, s7_read_t peek, s7_pointer port)
{
  return(<em class=red>s7_make_character</em>(sc, fgetc(stdin)));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();  

  <em class=red>s7_set_current_output_port</em>(s7, <em class=red>s7_open_output_function</em>(s7, my_print));
  s7_define_variable(s7, "io-port", <em class=red>s7_open_input_function</em>(s7, my_read));

  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *    &gt; (+ 1 2)
 *    [3]
 *    &gt; (display "hiho")
 *    [h] [i] [h] [o] [#] [&lt;] [u] [n] [s] [p] [e] [c] [i] [f] [i] [e] [d] [&gt;] 
 *    &gt; (define (add1 x) (+ 1 x))
 *    [a] [d] [d] [1] 
 *    &gt; (add1 123)
 *    [1] [2] [4] 
 *    &gt; (read-char io-port)
 *    a                             ; here I typed "a" in the shell
 *    [#] [\] [a] 
 */
</pre></div>





<div class="header" id="extendop"><h4>Extend a built-in operator ("+" in this case)</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer old_add;           /* the original "+" function for non-string cases */
static s7_pointer old_string_append; /* same, for "string-append" */

static s7_pointer our_add(s7_scheme *sc, s7_pointer args)
{
  /* this will replace the built-in "+" operator, extending it to include strings:
   *   (+ "hi" "ho") -&gt; "hiho" and  (+ 3 4) -&gt; 7
   */
  if ((s7_is_pair(args)) &amp;&amp;
      (s7_is_string(s7_car(args))))
    return(<em class=red>s7_apply_function</em>(sc, old_string_append, args));

  return(s7_apply_function(sc, old_add, args));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();

  /* get built-in + and string-append */
  old_add = s7_name_to_value(s7, "+");      
  old_string_append = s7_name_to_value(s7, "string-append");

  /* redefine "+" */
  s7_define_function(s7, "+", our_add, 0, 0, true, "(+ ...) adds or appends its arguments");

  while (1)
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *    &gt; (+ 1 2)
 *    3
 *    &gt; (+ "hi" "ho")
 *    "hiho"
 */
</pre></div>





<div class="header" id="definestar1"><h4>C-side define* (s7_define_function_star)</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer plus(s7_scheme *sc, s7_pointer args)
{
  /* (define* (plus (red 32) blue) (+ (* 2 red) blue)) */
  return(s7_make_integer(sc, 2 * s7_integer(s7_car(args)) + s7_integer(s7_car(s7_cdr(args)))));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();
  <em class=red>s7_define_function_star</em>(s7, "plus", plus, "(red 32) blue", "an example of define* from C");

  while (1)
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *    &gt; (plus 2 3)
 *    7
 *    &gt; (plus :blue 3)
 *    67
 *    &gt; (plus :blue 1 :red 4)
 *    9
 *    &gt; (plus 2 :blue 3)
 *    7
 *    &gt; (plus :blue 3 :red 1)
 *    5
 */
</pre></div>





<div class="header" id="definemacro1"><h4>C-side define-macro (s7_define_macro)</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer plus(s7_scheme *sc, s7_pointer args)
{
  /* (define-macro (plus a b) `(+ ,a ,b)) */
  s7_pointer a, b;
  a = s7_car(args);
  b = s7_car(s7_cdr(args));
  return(s7_list(sc, 3, s7_make_symbol(sc, "+"),  a, b));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();
  <em class=red>s7_define_macro</em>(s7, "plus", plus, 2, 0, false, "plus adds its two arguments");

  while (1)
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *    &gt; (plus 2 3)
 *    5
 */
</pre></div>



<div class="header" id="definegeneric"><h4>define a generic function in C</h4></div>

<p>In scheme, a function becomes generic simply by <code>(apply ((car args) 'func) args)</code>.
To accomplish the same thing in C, we use s7_search_open_environment and s7_apply_function:
</p>

<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer plus(s7_scheme *sc, s7_pointer args)
{
  #define plus_help "(plus obj ...) applies obj's plus method to obj and any trailing arguments."
  s7_pointer obj;
  obj = s7_car(args);
  if (<em class=red>s7_is_open_environment</em>(obj))          /* does obj have methods? */
    {
      s7_pointer method;                    /* does it have a 'plus method? */
      method = <em class=red>s7_search_open_environment</em>(sc, s7_make_symbol(sc, "plus"), obj);
      if (s7_is_procedure(method))
	return(<em class=red>s7_apply_function</em>(sc, method, args));
    }
  return(s7_f(sc));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  s7 = s7_init();
  s7_define_function(s7, "plus", plus, 1, 0, true, plus_help);
  while (1)
    {
      char buffer[512];
      char response[1024];
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* gcc -c s7.c -I.
 * gcc -o ex15 ex15.c s7.o -I. -lm -ldl
 *
 * &gt; (plus 1 2)
 * #f
 * (define obj (open-environment 
 *               (environment
 *                 (cons 'plus (lambda args 
 *                               (apply + 1 (cdr args)))))))
 * obj
 * &gt; (plus obj 2 3)
 * 6
 */
</pre>
</div>



<div class="header" id="signal"><h4>Signal handling and continuations</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;signal.h&gt;

#include "s7.h"

static s7_scheme *s7;
struct sigaction new_act, old_act;  
  
static void handle_sigint(int ignored)  
{  
  fprintf(stderr, "interrupted!\n");
  s7_symbol_set_value(s7, s7_make_symbol(s7, "*interrupt*"), <em class=red>s7_make_continuation</em>(s7)); /* save where we were interrupted */
  sigaction(SIGINT, &amp;new_act, NULL);  
  s7_quit(s7);                             /* get out of the eval loop if possible */
}  

static s7_pointer our_sleep(s7_scheme *sc, s7_pointer args)
{
  /* slow down our infinite loop for demo purposes */
  sleep(1);
  return(s7_f(sc));
}

int main(int argc, char **argv)
{
  char buffer[512];
  char response[1024];

  s7 = s7_init();
  s7_define_function(s7, "sleep", our_sleep, 0, 0, false, "(sleep) sleeps");
  s7_define_variable(s7, "*interrupt*", s7_f(s7)); 
  /* Scheme variable *interrupt* holds the continuation at the point of the interrupt */

  sigaction(SIGINT, NULL, &amp;old_act);
  if (old_act.sa_handler != SIG_IGN)
    {
      memset(&amp;new_act, 0, sizeof(new_act));  
      new_act.sa_handler = &amp;handle_sigint;  
      sigaction(SIGINT, &amp;new_act, NULL);  
    }

  while (1)
    {
      fprintf(stderr, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/*
 *    &gt; (do ((i 0 (+ i 1))) ((= i -1)) (format #t "~D " i) (sleep))
 *      ;;; now type C-C to break out of this loop
 *    0 1 2 ^Cinterrupted!
 *      ;;; call the continuation to continue from where we were interrupted
 *    &gt; (*interrupt*)
 *    3 4 5 ^Cinterrupted!
 *    &gt; *interrupt*
 *    #&lt;continuation&gt;
 *    &gt; (+ 1 2)
 *    3
 */
</pre></div>





<div class="header" id="vector"><h4>Multidimensional vector element access</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdarg.h&gt;

#include "s7.h"

static s7_pointer multivector_ref(s7_scheme *sc, s7_pointer vector, int indices, ...)
{
  /* multivector_ref returns an element of a multidimensional vector */
  int ndims;
  ndims = <em class=red>s7_vector_rank</em>(vector);

  if (ndims == indices)
    {
      va_list ap;
      s7_Int index = 0;
      va_start(ap, indices);

      if (ndims == 1)
	{
	  index = va_arg(ap, s7_Int);
	  va_end(ap);
	  return(s7_vector_ref(sc, vector, index));
	}
      else
	{
	  int i;
	  s7_pointer *elements;
	  s7_Int *offsets, *dimensions;

	  elements = <em class=red>s7_vector_elements</em>(vector);
	  dimensions = <em class=red>s7_vector_dimensions</em>(vector);
	  offsets = <em class=red>s7_vector_offsets</em>(vector);

	  for (i = 0; i &lt; indices; i++)
	    {
	      int ind;
	      ind = va_arg(ap, int);
	      if ((ind &lt; 0) ||
		  (ind &gt;= dimensions[i]))
		{
		  va_end(ap);
		  return(s7_out_of_range_error(sc, 
                                               "multivector_ref", i, 
                                               s7_make_integer(sc, ind), 
                                               "index should be between 0 and the dimension size"));
		}
	      index += (ind * offsets[i]);
	    }
	  va_end(ap);
	  return(elements[index]);
	}
    }
  return(s7_wrong_number_of_args_error(sc, 
                                       "multivector_ref: wrong number of indices: ~A", 
                                       s7_make_integer(sc, indices)));
}

int main(int argc, char **argv)
{
  char buffer[512];
  char response[1024];
  s7_scheme *s7;

  s7 = s7_init(); 
  s7_eval_c_string(s7, "(define vect (make-vector '(2 3 4) 0))");
  s7_eval_c_string(s7, "(set! (vect 1 1 1) 32)");

  fprintf(stdout, "vect[0,0,0]: %s, vect[1,1,1]: %s\n",
	  s7_object_to_c_string(s7, <em class=red>multivector_ref</em>(s7, s7_name_to_value(s7, "vect"), 3, 0, 0, 0)),
	  s7_object_to_c_string(s7, <em class=red>multivector_ref</em>(s7, s7_name_to_value(s7, "vect"), 3, 1, 1, 1)));
}

/* vect[0,0,0]: 0, vect[1,1,1]: 32
 */
</pre>
</div>

<p>Much later... I decided to add s7_vector_ref_n and s7_vector_set_n to s7.
</p>






<div class="header" id="notify"><h4>Notification from Scheme that a given Scheme variable has been set</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer scheme_set_notification(s7_scheme *sc, s7_pointer args)
{
  /* this function is called when the Scheme variable is set! */
  fprintf(stderr, "%s set to %s\n",
	  s7_object_to_c_string(sc, s7_car(args)),
	  s7_object_to_c_string(sc, s7_car(s7_cdr(args))));
  return(s7_car(s7_cdr(args)));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  s7 = s7_init();  

  s7_define_function(s7, "notify-C", scheme_set_notification, 2, 0, false, "called if notified-var is set!");
  s7_define_variable(s7, "notified-var", s7_make_integer(s7, 0));
  <em class=red>s7_symbol_set_access</em>(s7,   /* set symbol-access of notified-var to (list #f notify-C #f) */
		       s7_make_symbol(s7, "notified-var"),
		       s7_list(s7, 3, s7_f(s7), s7_name_to_value(s7, "notify-C"), s7_f(s7)));

  if (argc == 2)
    {
      fprintf(stderr, "load %s\n", argv[1]);
      s7_load(s7, argv[1]);
    }
  else
    {
      char buffer[512];
      char response[1024];
      while (1) 
	{
	  fprintf(stdout, "\n&gt; ");
	  fgets(buffer, 512, stdin);
	  
	  if ((buffer[0] != '\n') || 
	      (strlen(buffer) &gt; 1))
	    {                            
	      sprintf(response, "(write %s)", buffer);
	      s7_eval_c_string(s7, response);
	    }
	}
    }
}

/*    &gt; notified-var
 *    0
 *    &gt; (set! notified-var 32)
 *    notified-var set to 32
 *    32
 */
</pre></div>





<div class="header" id="namespace"><h4>Load C defined stuff into a separate namespace</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer func1(s7_scheme *sc, s7_pointer args)
{
  return(s7_make_integer(sc, s7_integer(s7_car(args)) + 1));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  s7_pointer new_env;

  s7 = s7_init();  

  /* "func1" and "var1" will be placed in an anonymous environment,
   *   accessible from Scheme via the global variable "lib-exports"
   */
  
  new_env = <em class=red>s7_augment_environment</em>(s7, s7_current_environment(s7), s7_nil(s7));
  /* make a private environment for func1 and var1 below (this is our "namespace") */
  s7_gc_protect(s7, new_env);

  s7_define(s7, <em class=red>new_env</em>, 
	    s7_make_symbol(s7, "func1"),
	    <em class=red>s7_make_function</em>(s7, "func1", func1, 1, 0, false, "func1 adds 1 to its argument"));
  
  s7_define(s7, <em class=red>new_env</em>, s7_make_symbol(s7, "var1"), s7_make_integer(s7, 32));
  /* those two symbols are now defined in the new environment */

  /* add "lib-exports" to the global environment */
  s7_define_variable(s7, "lib-exports", <em class=red>s7_environment_to_list</em>(s7, new_env));

  if (argc == 2)
    {
      fprintf(stderr, "load %s\n", argv[1]);
      s7_load(s7, argv[1]);
    }
  else
    {
      char buffer[512];
      char response[1024];
      while (1) 
	{
	  fprintf(stdout, "\n&gt; ");
	  fgets(buffer, 512, stdin);
	  
	  if ((buffer[0] != '\n') || 
	      (strlen(buffer) &gt; 1))
	    {                            
	      sprintf(response, "(write %s)", buffer);
	      s7_eval_c_string(s7, response);
	    }
	}
    }
}

/*     &gt; func1
 *     ;func1: unbound variable, line 1
 *     &gt; lib-exports
 *     ((var1 . 32) (func1 . func1))
 *     ;; so lib-exports has the C-defined names and values
 *     ;; we can use these directly:
 *
 *     &gt; (define lib-env (apply <em class=red>augment-environment</em> (current-environment) lib-exports))
 *     lib-env
 *     &gt; (<em class=red>with-environment</em> lib-env (func1 var1))
 *     33
 *
 *     ;; or rename them to prepend "lib:"
 *     &gt; (define lib-env (apply augment-environment 
                                (current-environment) 
                                (map (lambda (binding) 
                                       (cons (string-&gt;symbol 
                                               (string-append "lib:" (symbol-&gt;string (car binding)))) 
                                             (cdr binding))) 
                                     lib-exports)))
 *     lib-env
 *     &gt; (with-environment lib-env (lib:func1 lib:var1))
 *     33
 *
 *     ;;; now for convenience, place "func1" in the global environment under the name "func2"
 *     &gt; (define func2 (cdadr lib-exports)) 
 *     func2
 *     &gt; (func2 1)  
 *     2
 */
</pre></div>





<div class="header" id="Cerrors"><h4>Handle scheme errors in C</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer error_handler(s7_scheme *sc, s7_pointer args)
{
  fprintf(stdout, "error: %s\n", s7_string(s7_car(args)));
  return(s7_f(sc));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];
  bool with_error_hook = false;

  s7 = s7_init();  
  s7_define_function(s7, "error-handler", error_handler, 1, 0, false, "our error handler");

  if (with_error_hook)
    s7_eval_c_string(s7, "(set! (hook-functions *error-hook*)                    \n\
                            (list (lambda (hook)                                 \n\
                                    (error-handler                               \n\
                                      (apply format #f (hook 'data)))            \n\
                                    (set! (hook 'result) 'our-error))))");
  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
	  
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  s7_pointer old_port, result;
	  int gc_loc = -1;
	  const char *errmsg = NULL;

	  /* trap error messages */
	  old_port = s7_set_current_error_port(s7, s7_open_output_string(s7));
	  if (old_port != s7_nil(s7))
	    gc_loc = s7_gc_protect(s7, old_port);

	  /* evaluate the input string */
	  result = s7_eval_c_string(s7, buffer);

	  /* print out the value wrapped in "{}" so we can tell it from other IO paths */
	  fprintf(stdout, "{%s}", s7_object_to_c_string(s7, result));

	  /* look for error messages */
	  errmsg = s7_get_output_string(s7, s7_current_error_port(s7));

	  /* if we got something, wrap it in "[]" */
	  if ((errmsg) &amp;&amp; (*errmsg))
	    fprintf(stdout, "[%s]", errmsg); 

	  s7_close_output_port(s7, s7_current_error_port(s7));
	  s7_set_current_error_port(s7, old_port);
	  if (gc_loc != -1)
	    s7_gc_unprotect_at(s7, gc_loc);
	}
    }
}

/* 
 *   gcc -c s7.c -I. -g3
 *   gcc -o ex3 ex3.c s7.o -lm -I. -ldl
 *
 * if with_error_hook is false,
 *
 *   &gt; (+ 1 2)
 *   {3}
 *   &gt; (+ 1 #\c)
 *   {wrong-type-arg}[
 *   ;+ argument 2, #\c, is character but should be a number, line 1
 *   ]
 *
 * so s7 by default prepends ";" to the error message, and appends "\n",
 *   sending that to current-error-port, and the error type ('wrong-type-arg here)
 *   is returned.
 *
 * if with_error_hook is true,
 *
 *   &gt; (+ 1 2)
 *   {3}
 *   &gt; (+ 1 #\c)
 *   error: + argument 2, #\c, is character but should be a number
 *   {our-error}
 *
 * so now the *error-hook* code handles both the error reporting and
 *   the value returned ('our-error in this case).
 */
</pre></div>





<div class="header" id="closure"><h4>Closures in C</h4></div>

<p>We often have hooks or callback lists in Scheme, and would like to place a C-defined
s7 function on such a list.  If the C-side function does not have
any state, we can just add its name to the list, but if it is effectively a closure, we have a problem.  C itself does not
provide closures, so the standard two-step is to include a void* pointer with the
C function in a struct, then when that is called, pass the pointer to the function
by hand.  This obviously does not work if we want that function to be a member of
a normal Scheme list of functions.  So in the next example, we define a closure
in C using s7_make_closure.  
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer closure_func(s7_scheme *sc, s7_pointer args)
{
  /* closure_func is the function portion of our closure.  It assumes its
   *   environment has an integer named "x".  The function also takes one argument,
   *   an integer we'll call it "y".
   */
  return(s7_make_integer(sc,                            /* return (+ y x) */
                         s7_integer(s7_car(args)) +     /*   this is y */
                         s7_integer(s7_name_to_value(sc, "x"))));
}

static s7_pointer define_closure(s7_scheme *sc, const char *name, s7_pointer func, s7_pointer x_value)
{
  /* make_closure creates a new closure with x_value as the local value of x,
   *   and func as the function.  It defines this in Scheme as "name".  
   *
   *   s7_make_closure's arguments are the closure args and body, and
   *   the closure's environment.  For the args, we'll use '(y), and
   *   the body is '(f y));  for the environment, we'll augment 
   *   the current environment with '((x . x_value) (f . func)).
   */
  s7_define(sc, 
	    s7_nil(sc),
	    s7_make_symbol(sc, name),
	    <em class=red>s7_make_closure</em>(sc, 
			    s7_cons(sc,                         /* arg list: '(y) */
			            s7_make_symbol(sc, "y"), s7_nil(sc)), 
			    s7_cons(sc,                         /* body: '(f y) */
				    s7_cons(sc,                              
					    s7_make_symbol(sc, "f"),
					    s7_cons(sc, s7_make_symbol(sc, "y"), s7_nil(sc))),
				    s7_nil(sc)),
			    <em class=red>s7_augment_environment</em>(sc, 
						   s7_current_environment(sc), 
						   s7_cons(sc, 
							   s7_cons(sc,  /* the local binding for "x" */
                                                                   s7_make_symbol(sc, "x"), 
                                                                   <em class=red>x_value</em>), 
							   s7_cons(sc,  /*     and "f" */
								   s7_cons(sc, 
                                                                           s7_make_symbol(sc, "f"), 
                                                                           <em class=red>func</em>), 
								   s7_nil(sc))))));
  return(s7_unspecified(sc));
}

int main(int argc, char **argv)
{
  char buffer[512];
  char response[1024];
  s7_pointer c_func;
  s7_scheme *s7;

  s7 = s7_init();  

  c_func = s7_make_function(s7, "#&lt;closure function&gt;", closure_func, 1, 0, false, "function used by define_closure");

  define_closure(s7, "closure-1", c_func, s7_make_integer(s7, 32));  /* (let ((x 32)) (lambda (y) (+ y x))) */
  define_closure(s7, "closure-2", c_func, s7_make_integer(s7, 123)); /* (let ((x 123)) (lambda (y) (+ y x))) */

  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/*
 *   &gt; (closure-1 3)
 *   35
 *   &gt; (closure-2 3)
 *   126
 *   &gt; (procedure-source closure-1)
 *   (lambda (y) (f y))
 *   &gt; (environment-&gt;list (procedure-environment closure-1))
 *   ((f . #&lt;closure function&gt;) (x . 32))
 */
</pre></div>





<div class="header" id="testhook"><h4>C and Scheme hooks</h4></div>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

static s7_pointer my_hook_function(s7_scheme *sc, s7_pointer args)
{
  fprintf(stderr, "a is %s\n", s7_object_to_c_string(sc, s7_symbol_local_value(sc, s7_make_symbol(sc, "a"), s7_car(args))));
  return(s7_car(args));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];
  s7_pointer test_hook;

  s7 = s7_init();  

  /* define test_hook in C, test-hook in Scheme, arguments are named a and b */
  test_hook = <em class=red>s7_eval_c_string</em>(s7, "(make-hook 'a 'b)");
  s7_define_constant(s7, "test-hook", test_hook); 

  /* add my_hook_function to the test_hook function list */
  <em class=red>s7_hook_set_functions</em>(s7, test_hook, 
			s7_cons(s7, 
				s7_make_function(s7, "my-hook-function", my_hook_function, 1, 0, false, "my hook-function"), 
				s7_hook_functions(s7, test_hook)));
  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
	  
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *    &gt; test-hook
 *    #&lt;lambda (hook)&gt;
 *    
 *    &gt; (hook-functions test-hook)
 *    (my-hook-function)
 *
 *    &gt; (test-hook 1 2)
 *    a is 1
 *    #&lt;unspecified&gt;
 */
</pre></div>





<div class="header" id="dload"><h4>Load a shared library</h4></div>

<p>We can use dlopen to load a shared library, and dlsym to initialize
that library in our main program.  The tricky part is to conjure up the right
compiler and loader flags.
First we define a module that defines a new s7 function, add-1 that we'll tie
into s7 explicitly, and another
function that we'll try to call by waving a wand.
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"

double a_function(double an_arg);
double a_function(double an_arg)
{
  return(an_arg + 1.0);
}

static s7_pointer add_1(s7_scheme *sc, s7_pointer args) 
{
  return(s7_make_integer(sc, s7_integer(s7_car(args)) + 1)); 
}

void init_ex(s7_scheme *sc);
void init_ex(s7_scheme *sc)  /* this needs to be globally accessible (not "static") */
{
  /* tell s7 about add-1, but leave a_function hidden */
  s7_define_function(sc, "add-1", add_1, 1, 0, false, "(add-1 x) adds 1 to x");
}

</pre></div>


<p>And here is our main program:
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include "s7.h"
#include &lt;dlfcn.h&gt;

static void *library = NULL;

static s7_pointer try(s7_scheme *sc, s7_pointer args)
{
  /* try tries to call an arbitrary function in the shared library */
  void *func;
  func = <em class=red>dlsym</em>(library, s7_string(s7_car(args)));
  if (func)
    {
      /* we'll assume double f(double) */
      typedef double (*dl_func)(double arg);
      return(s7_make_real(sc, ((dl_func)<em class=red>func</em>)(s7_real(s7_cadr(args)))));
    }
  return(s7_error(sc, s7_make_symbol(sc, "can't find function"), 
		  s7_list(sc, 2, s7_make_string(sc, "loader error: ~S"), 
			         s7_make_string(sc, dlerror()))));
}

static s7_pointer cload(s7_scheme *sc, s7_pointer args)
{
  /* cload loads a shared library */
  #define CLOAD_HELP "(cload so-file-name) loads the module"
  library = dlopen(s7_string(s7_car(args)), RTLD_LAZY);
  if (library)
    {
      /* call our init func to define add-1 in s7 */
      void *init_func;
      init_func = <em class=red>dlsym</em>(library, s7_string(s7_car(s7_cdr(args))));
      if (init_func)
	{
	  typedef void *(*dl_func)(s7_scheme *sc);
	  ((dl_func)<em class=red>init_func</em>)(sc);  /* call the initialization function (init_ex above) */
	  return(s7_t(sc));
	}
    }
  return(s7_error(sc, s7_make_symbol(sc, "load-error"), 
		      s7_list(sc, 2, s7_make_string(sc, "loader error: ~S"), 
			             s7_make_string(sc, dlerror()))));
}

int main(int argc, char **argv)
{
  char buffer[512];
  char response[1024];
  s7_scheme *s7;

  s7 = s7_init();  

  s7_define_function(s7, "cload", cload, 2, 0, false, CLOAD_HELP);
  s7_define_function(s7, "try", try, 2, 0, false, 
                         "(try name num) tries to call name in the shared library with the argument num.");

  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
	  
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* Put the module in the file ex3a.c and the main program in ex3.c, then
 *
 * in Linux:
 *   gcc -c -fPIC ex3a.c
 *   gcc ex3a.o -shared -o ex3a.so
 *   gcc -c s7.c -I. -fPIC -shared
 *   gcc -o ex3 ex3.c s7.o -lm -ldl -I. -Wl,-export-dynamic
 *
 * in Mac OSX:
 *   gcc -c ex3a.c
 *   gcc ex3a.o -o ex3a.so -dynamic -bundle -undefined suppress -flat_namespace
 *   gcc -c s7.c -I. -dynamic -bundle -undefined suppress -flat_namespace
 *   gcc -o ex3 ex3.c s7.o -lm -ldl -I.
 *
 * and run it:
 *   ex3
 *   &gt; (cload "/home/bil/snd-14/ex3a.so" "init_ex")
 *   #t
 *   &gt; (add-1 2)
 *   3
 *   &gt; (try "a_function" 2.5)
 *   3.5
 */
</pre></div>

<p>All of this is just boring boilerplate, so with a little support from s7,
we can write a script to do the entire linkage.  The s7 side is an extension
to "load" that loads a shared object file if its extension is "so", and
runs an initialization function whose name is defined in the load
environment (the optional second argument to load).  An example of the scheme side is cload.scm,
included in the s7 tarball.  It defines a function that can be
called:
</p>

<pre class="indented">
(c-define '(double j0 (double)) "m" "math.h")
</pre>

<p>This links the s7 function m:j0 to the math library
function j0.  See <a href="#cload">cload.scm</a> for more details.
</p>



<div class="header" id="gmpex"><h4>Bignums in C</h4></div>

<p>Bignum support depends on gmp, mpfr, and mpc.  In this example, we define "add-1" which adds
1 to any kind of number.  The s7_big_* functions return the underlying gmp/mpfr/mpc pointer,
so we have to copy that into a new number before adding.
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include &lt;gmp.h&gt;
#include &lt;mpfr.h&gt;
#include &lt;mpc.h&gt;

#include "s7.h"

static s7_pointer big_add_1(s7_scheme *sc, s7_pointer args)
{
  /* add 1 to either a normal number or a bignum */
  s7_pointer x;
  x = s7_car(args);
  if (s7_is_bignum(x))
    {
      s7_pointer n;
      if (s7_is_integer(x))
	{
	  mpz_t *big_n;
	  n = s7_make_big_integer(sc, s7_big_integer(x)); /* copy x */
	  big_n = s7_big_integer(n);                      /* get mpz_t pointer of copy */
	  mpz_add_ui(*big_n, *big_n, 1);                  /* add 1 to that */
	  return(n);                                      /* return the new bignum */
	}
      if (s7_is_ratio(x))
	{
	  mpq_t *big_q;
	  mpz_t num, den;
	  n = s7_make_big_ratio(sc, s7_big_ratio(x));
	  big_q = s7_big_ratio(n);
	  mpz_init_set(num, mpq_numref(*big_q));
	  mpz_init_set(den, mpq_denref(*big_q));
	  mpz_add(num, num, den);
	  mpq_set_num(*big_q, num);
	  mpz_clear(num);
	  mpz_clear(den);
	  return(n);
	}
      if (s7_is_real(x))
	{
	  mpfr_t *big_x;
	  n = s7_make_big_real(sc, s7_big_real(x));
	  big_x = s7_big_real(n);
	  mpfr_add_ui(*big_x, *big_x, 1, GMP_RNDN);
	  return(n);
	}
      /* x must be big complex */
      {
	mpc_t *big_z;
	n = s7_make_big_complex(sc, s7_big_complex(x));
	big_z = s7_big_complex(n);
	mpc_add_ui(*big_z, *big_z, 1, MPC_RNDNN);
	return(n);
      }
    }
  else
    {
      if (s7_is_integer(x))
	return(s7_make_integer(sc, 1 + s7_integer(x)));
      if (s7_is_rational(x))
	return(s7_make_ratio(sc, s7_numerator(x) + s7_denominator(x), s7_denominator(x)));
      if (s7_is_real(x))
	return(s7_make_real(sc, 1.0 + s7_real(x)));
      if (s7_is_complex(x))
	return(s7_make_complex(sc, 1.0 + s7_real_part(x), s7_imag_part(x)));
    }
  return(s7_wrong_type_arg_error(sc, "add-1", 0, x, "a number"));
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  char buffer[512];
  char response[1024];

  s7 = s7_init();  
  s7_define_function(s7, "add-1", big_add_1, 1, 0, false, "(add-1 num) adds 1 to num");

  while (1) 
    {
      fprintf(stdout, "\n&gt; ");
      fgets(buffer, 512, stdin);
      if ((buffer[0] != '\n') || 
	  (strlen(buffer) &gt; 1))
	{                            
	  sprintf(response, "(write %s)", buffer);
	  s7_eval_c_string(s7, response);
	}
    }
}

/* 
 *   gcc -DWITH_GMP=1 -c s7.c -I. -O2 -g3
 *   gcc -DWITH_GMP=1 -o ex2 ex2.c s7.o -I. -O2 -lm -ldl -lgmp -lmpfr -lmpc
 *
 *   ex2
 *   &gt; (add-1 1)   
 *   2
 *   &gt; (add-1 2/3)
 *   5/3
 *   &gt; (add-1 1.4) 
 *   2.4
 *   &gt; (add-1 1.5+i)
 *   2.5+1i
 *   &gt; (add-1 (bignum "3"))
 *   4          ; this is the bignum 4
 *   &gt; (add-1 (bignum "3/4"))
 *   7/4
 *   &gt; (add-1 (bignum "1.4"))
 *   2.399999999999999911182158029987476766109E0
 *   &gt; (add-1 (bignum "1.5+i"))
 *   2.500E0+1.000E0i
 */
</pre></div>





<div class="header" id="gtkrepl"><h4>gtk-based repl</h4></div>

<p>In this example, we use Gtk to make a window with a scrolled text widget, running s7
in a read-eval-print loop.  I've tried to make this as short as possible; see glistener.c for
a much more elaborate REPL.  From s7's point of view, the only tricky part involves
catching errors.
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

/* use Gtk to post a text widget as a REPL.
 */
#include &lt;gtk/gtk.h&gt;

#if HAVE_GTK_3
  #include &lt;gdk/gdk.h&gt;
  #define Return_Key GDK_KEY_Return
#else
  #include &lt;gdk/gdkkeysyms.h&gt;
  #define Return_Key GDK_Return
#endif

#include "s7.h"

#define S7_PROMPT "s7&gt; "
#define S7_PROMPT_LENGTH 4

static GtkWidget* repl;                        /* the REPL text widget */
static GtkTextBuffer *repl_buf;                /* its text buffer */
static GtkTextTag *prompt_not_editable = NULL; /* a tag to make sure the prompt can't be erased */

static gint quit_repl(GtkWidget *w, GdkEvent *event, gpointer context)
{
  /* called when we click the 'x' window decoration */
  exit(0);
}

static void evaluate_expression(s7_scheme *sc, char *expression)
{
  /* evaluate expression, display result, catching and displaying any errors */
  if ((expression) &amp;&amp;
      (*expression))
    {
      if ((strlen(expression) &gt; 1) || 
	  (expression[0] != '\n'))
	{
	  const char *errmsg;
	  int gc_loc = -1;
	  s7_pointer old_port, result;
	  GtkTextIter pos;

	  /* open a port to catch error info */
	  old_port = s7_set_current_error_port(sc, s7_open_output_string(sc));
	  if (old_port != s7_nil(sc))
	    gc_loc = s7_gc_protect(sc, old_port);
	  
	  result = s7_eval_c_string(sc, expression);
	  
	  errmsg = s7_get_output_string(sc, s7_current_error_port(sc));
	  /* if error, display it, else display result of evaluation */
	  gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);
	  
	  if ((errmsg) &amp;&amp; (*errmsg))
	    gtk_text_buffer_insert(repl_buf, &amp;pos, errmsg, strlen(errmsg));
	  else 
	    {
	      char *result_as_string;
	      result_as_string = s7_object_to_c_string(sc, result);
	      if (result_as_string)
		{
		  gtk_text_buffer_insert(repl_buf, &amp;pos, "\n", 1);
		  gtk_text_buffer_insert(repl_buf, &amp;pos, result_as_string, strlen(result_as_string));
		  free(result_as_string);
		}
	    }
	  
	  s7_close_output_port(sc, s7_current_error_port(sc));
	  s7_set_current_error_port(sc, old_port);
	  if (gc_loc != -1)
	    s7_gc_unprotect_at(sc, gc_loc);
	}
      g_free(expression);
    }
}

static char *get_current_expression(void)
{
  /* find the enclosing expression and return it.  This could be a lot smarter, but
   *    for now, I'll just look back to the previous prompt, then forward for the 
   *    next prompt or the buffer end.
   */
  GtkTextIter pos, previous, next, temp;
  GtkTextMark *m;

  m = gtk_text_buffer_get_insert(repl_buf);
  gtk_text_buffer_get_iter_at_mark(repl_buf, &amp;pos, m);

  if (gtk_text_iter_backward_search(&amp;pos, S7_PROMPT, 0, &amp;temp, &amp;previous, NULL))
    {
      /* previous now marks the end of the previous prompt */
      if (!gtk_text_iter_forward_search(&amp;pos, S7_PROMPT, 0, &amp;next, &amp;temp, NULL))
	{
	  gtk_text_buffer_get_end_iter(repl_buf, &amp;next);
	  /* next now marks the end of the buffer, so there's no complication */
	  return(gtk_text_buffer_get_text(repl_buf, &amp;previous, &amp;next, true));
	}
      /* here next marks the start of the next prompt, but that probably includes
       *   the result printout from an earlier evaluation.  s7_eval_c_string evaluates
       *   all the expressions in its string, returning the value of the last one,
       *   but we want the first.  We'll backup two '\n'.
       */
      gtk_text_iter_backward_search(&amp;next, "\n", 0, &amp;pos, &amp;temp, NULL);     
      gtk_text_iter_backward_search(&amp;pos, "\n", 0, &amp;next, &amp;temp, NULL);      
      return(gtk_text_buffer_get_text(repl_buf, &amp;previous, &amp;next, true));
    }
  return(NULL);
}

static gboolean repl_key_press(GtkWidget *w, GdkEventKey *event, gpointer scheme)
{
  /* called when we type anything in the text widget.
   *   'scheme' is our s7 interpreter.
   */
  guint key;
  key = event-&gt;keyval;
  if (key == Return_Key)
    {
      GtkTextIter pos;
      /* get enclosing expression, evaluate it, display result (or error), prompt for next */
      evaluate_expression((s7_scheme *)scheme, get_current_expression());

      /* prompt for next expression */
      gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);
      gtk_text_buffer_insert_with_tags(repl_buf, &amp;pos, 
                                       "\n" S7_PROMPT, 1 + S7_PROMPT_LENGTH, prompt_not_editable, NULL);

      /* make sure the stuff we added is visible */
      gtk_text_buffer_place_cursor(repl_buf, &amp;pos);
      gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(repl), gtk_text_buffer_get_insert(repl_buf));

      /* tell Gtk that we already sent the '\n' */
      g_signal_stop_emission((gpointer)w, 
                             g_signal_lookup("key_press_event", G_OBJECT_TYPE((gpointer)w)), 0);
    }
  return(false);
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  GtkWidget *shell, *scrolled_window;
  GtkTextIter pos;

  s7 = s7_init();  

  /* make a window with a scrolled text widget */
  gtk_init(&amp;argc, &amp;argv);
  shell = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(G_OBJECT(shell), "delete_event", G_CALLBACK(quit_repl), NULL);

  scrolled_window = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), 
                                 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_container_add(GTK_CONTAINER(shell), scrolled_window);

  repl = gtk_text_view_new();
  repl_buf = gtk_text_buffer_new(NULL);
  gtk_container_add(GTK_CONTAINER(scrolled_window), repl);

  gtk_text_view_set_buffer(GTK_TEXT_VIEW(repl), repl_buf);
  gtk_text_view_set_editable(GTK_TEXT_VIEW(repl), true);
  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(repl), GTK_WRAP_NONE);
  gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(repl), true);
  gtk_text_view_set_left_margin(GTK_TEXT_VIEW(repl), 4);

  /* whenever a key is pressed, call repl_key_press */
  gtk_widget_set_events(repl, GDK_ALL_EVENTS_MASK);
  g_signal_connect(G_OBJECT(repl), "key_press_event", G_CALLBACK(repl_key_press), (void *)s7);

  gtk_widget_show(repl);
  gtk_widget_show(scrolled_window);
  gtk_widget_show(shell);

  /* start with a boldface '&gt;' prompt that can't be stepped on */
  prompt_not_editable = gtk_text_buffer_create_tag(repl_buf, "prompt_not_editable", 
						   "editable", false, 
						   "weight", PANGO_WEIGHT_BOLD,
						   NULL);
  gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);
  gtk_text_buffer_insert_with_tags(repl_buf, &amp;pos, 
                                   S7_PROMPT, S7_PROMPT_LENGTH, prompt_not_editable, NULL);

  /* make the initial window size reasonable */
  gdk_window_resize(gtk_widget_get_window(shell), 400, 200);
  gtk_main();
}

/*   gcc -c s7.c -I. 
 *   gcc -o listener listener.c s7.o -I. `pkg-config --libs gtk+-3.0 --cflags` -lm -ldl
 */

</pre></div>





<div class="header" id="gtkschemerepl"><h4>scheme-based repl (using gtk)</h4></div>

<p>In the same vein, we can use libxm's Gtk/s7 bindings to make the REPL in Scheme.
Here is the same code, but now using libxm; first the C side, called gtkex.c:
</p>


<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#include &lt;mus-config.h&gt;
#include "xen.h"
void Init_libxg(void);

int main(int argc, char **argv)
{
  s7_scheme *s7;
  s7 = s7_init();             /* start s7 */
  s7_xen_initialize(s7);     /* start the xen connection to libxm */
  Init_libxg();              /* load up all the glib/gdk/gtk/cairo/pango bindings in libxm */
  s7_load(s7, "gtkex.scm");  /* load and run our REPL (below) */ 
}

/*   libxm: configure --with-gtk, then make
 *   gcc -o gtkex gtkex.c libxg.so -lm -ldl -I.
 *   ;; you may need to include the libxm directory above
 */
</pre></div>


<p>And here is gtkex.scm.  The main problem with this code is that Gtk is moving
rapidly toward gtk3, and libxm is running along behind panting and complaining.
There are several things that may change once Gtk settles down.
</p>


<div class="indented">
<pre>
(gtk_init 0 #f)

(let ((shell (gtk_window_new GTK_WINDOW_TOPLEVEL))
      (s7-prompt "s7&gt; ")
      (return-key (if (provided? 'gtk3) GDK_KEY_Return GDK_Return)))
  
  (g_signal_connect (G_OBJECT shell) "delete_event"
		    (lambda (window event data)
		      (gtk_main_quit)
		      (exit)))
  (g_signal_connect (G_OBJECT shell) "destroy" 
		    (lambda (window data)
		      (gtk_main_quit)
		      (exit)))
  
  (gtk_window_set_title (GTK_WINDOW shell) "s7")

  (let ((scrolled_window (gtk_scrolled_window_new #f #f)))
    
    (gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW scrolled_window) 
                                    GTK_POLICY_AUTOMATIC GTK_POLICY_AUTOMATIC)
    (gtk_container_add (GTK_CONTAINER shell) scrolled_window)
    
    (let* ((repl (gtk_text_view_new))
	   (repl_buf (gtk_text_buffer_new #f))
	   (prompt_not_editable #f))

      (define (evaluate-expression expr)
	(let ((pos (GtkTextIter))
	      (result (catch #t
			     (lambda ()
			       (object-&gt;string (eval-string expr)))
			     (lambda args
			       (format #f "~A: ~S" (car args) (apply format #f (cadr args)))))))
	  (gtk_text_buffer_get_end_iter repl_buf pos)
	  (gtk_text_buffer_insert repl_buf pos "\n" 1)
	  (gtk_text_buffer_insert repl_buf pos result (length result))))

      (define (get-current-expression)
	(let ((m (gtk_text_buffer_get_insert repl_buf))
	      (pos (GtkTextIter))
	      (previous (GtkTextIter))
	      (next (GtkTextIter))
	      (temp (GtkTextIter)))
	  (gtk_text_buffer_get_iter_at_mark repl_buf pos m)
	  (if (gtk_text_iter_backward_search pos s7-prompt 0 temp previous #f)
	      (if (not (gtk_text_iter_forward_search pos s7-prompt 0 next temp #f))
		  (begin
		    (gtk_text_buffer_get_end_iter repl_buf next)
		    (gtk_text_buffer_get_text repl_buf previous next #t))
		  (begin
		    (gtk_text_iter_backward_search next "\n" 0 pos temp #f)
		    (gtk_text_iter_backward_search pos "\n" 0 next temp #f)
		    (gtk_text_buffer_get_text repl_buf previous next #t)))
	      "")))

      (define (repl-key-press w event data)
	(let ((key (gtk_event_keyval event)))
	  (if (equal? key return-key)
	      (let ((pos (GtkTextIter)))

		(evaluate-expression (get-current-expression))
		
		(gtk_text_buffer_get_end_iter repl_buf pos)
		(gtk_text_buffer_insert_with_tags repl_buf pos
						  (string-append (string #\newline) s7-prompt) 
						  (+ 1  (length s7-prompt))
						  (list prompt_not_editable))
		(gtk_text_buffer_place_cursor repl_buf pos)
		(gtk_text_view_scroll_mark_onscreen (GTK_TEXT_VIEW repl) 
						    (gtk_text_buffer_get_insert repl_buf))
		(g_signal_stop_emission (GPOINTER w)
					(g_signal_lookup "key_press_event" 
							 (G_OBJECT_TYPE (G_OBJECT w))) 
					0)))))
      
      (gtk_container_add (GTK_CONTAINER scrolled_window) repl)
      (gtk_text_view_set_buffer (GTK_TEXT_VIEW repl) repl_buf)
      (gtk_text_view_set_editable (GTK_TEXT_VIEW repl) #t)
      (gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW repl) GTK_WRAP_NONE)
      (gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW repl) #t)
      (gtk_text_view_set_left_margin (GTK_TEXT_VIEW repl) 4)
      
      (gtk_widget_set_events repl GDK_ALL_EVENTS_MASK)
      (g_signal_connect (G_OBJECT repl) "key_press_event" repl-key-press)

      (gtk_widget_show repl)
      (gtk_widget_show scrolled_window)
      (gtk_widget_show shell)
      
      (set! prompt_not_editable 
	    (gtk_text_buffer_create_tag repl_buf "prompt_not_editable" 
					(list "editable" 0 "weight" PANGO_WEIGHT_BOLD)))
      (let ((pos (GtkTextIter)))
	(gtk_text_buffer_get_end_iter repl_buf pos)
	(gtk_text_buffer_insert_with_tags repl_buf pos 
					  s7-prompt (length s7-prompt)
					  (list prompt_not_editable))
	(gdk_window_resize (gtk_widget_get_window shell) 400 200)
	(gtk_main)))))

;; build gtkex as above, then run it and it will load/run this code
</pre>


<p>There is one major flaw in these two REPLs; if s7 gets caught in an infinite loop (via
<code>(do () ())</code> for example), you have to kill the main program to stop it.  We could use
Unix interrupts as in the <a href="#signal">signal</a> example earlier, but surely in a modern
GUI-based program, we'd like to avoid such brute-force stuff.  In particular, we want our interface
to keep running while we clean up the s7 problem.  On first thought, we might try to use a separate
thread for the s7 evaluation, but that won't solve the problem.
Any GUI callback can
call s7_call or s7_eval_c_string directly.  If the listener
starts a long evaluation (or falls into an infinite loop), and we start idly poking around 
with the mouse, waiting for the evaluation to finish, a mouse or menu callback can trigger
a call on the same s7 interpreter that is currently running in the listener.
We are trying to evaluate two different expressions at the same time!  What you
get depends on where s7 notices the problem.  If the evaluator senses that it is lost,
it will raise some confusing error; otherwise the s7 stack will cause a segfault.
We need the GUI to stay active so that we can interrupt computation by typing C-C.
We can't sort through all the events dispatching only the C-C, because that
confuses subsequent GUI actions, and the whole idea is to keep the interface
alive.  We can put the listener's s7_eval_c_string in a separate s7 thread
so that the multiple evaluations can be interleaved, but those evaluations
can still make calls into Gtk or Motif, and
unfortunately, neither GUI toolkit is thread-safe. If two threads invoke
a GUI function, you get a segfault or some other bizarre screwup.
So...
</p>
</div>


<div class="header" id="replrescue"><h4>begin-hook</h4></div>

<p>
Common Lisp has something called "evalhook" that makes it possible
to insert your own function into eval.  In s7, we have a "begin_hook" which sits at the opening of any begin block
(implicit or explicit).  Here are two REPLs, one for Gtk, and one for a bare terminal.
</p>





<div class="indented">
<pre>
/* terminal-based REPL, 
 *    an expansion of the <a href="#repl">read-eval-print loop</a> program above.
 * type C-g to interrupt an evaluation.
 */
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;termios.h&gt;
#include &lt;signal.h&gt;

#include "s7.h"

static struct termios save_buf, buf;

static void sigcatch(int n)
{
  /* put things back the way they were */
  tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
  exit(0);
}

static char buffer[512];
static int type_ahead_point = 0;

static void <em class=red>watch_for_c_g</em>(s7_scheme *sc, bool *all_done)
{
  char c;
  /* watch for C-g without blocking, save other chars as type-ahead */
  tcsetattr(fileno(stdin), TCSAFLUSH, &amp;buf);

  if (read(fileno(stdin), &amp;c, 1) == 1)
    {
      if (c == 7) /* C-g */
	{
	  *all_done = true;
	  type_ahead_point = 0;
	}
      else buffer[type_ahead_point++] = c;
    }

  tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
}

int main(int argc, char **argv)
{
  s7_scheme *s7;
  bool use_begin_hook;

  use_begin_hook = (tcgetattr(fileno(stdin), &amp;save_buf) &gt;= 0);
  if (use_begin_hook)
    {
      buf = save_buf;
      buf.c_lflag &amp;= ~ICANON;
      buf.c_cc[VMIN] = 0;         /* if no chars waiting, just return */
      buf.c_cc[VTIME] = 0;

      signal(SIGINT, sigcatch);
      signal(SIGQUIT, sigcatch);
      signal(SIGTERM, sigcatch);
    }

  s7 = s7_init();  

  if (argc == 2)
    {
      fprintf(stderr, "load %s\n", argv[1]);
      s7_load(s7, argv[1]);
    }
  else
    {
      char response[1024];
      while (1) 
	{
	  fprintf(stdout, "\n&gt; ");
	  fgets((char *)(buffer + type_ahead_point), 512 - type_ahead_point, stdin);
	  type_ahead_point = 0;

	  if ((buffer[0] != '\n') || 
	      (strlen(buffer) &gt; 1))
	    {                            
	      sprintf(response, "(write %s)", buffer);

	      if (use_begin_hook)
		<em class=red>s7_set_begin_hook</em>(s7, watch_for_c_g);
	      s7_eval_c_string(s7, response);
	      if (use_begin_hook)
		<em class=red>s7_set_begin_hook</em>(s7, NULL);
	    }
	}
    }
  if (use_begin_hook)
    tcsetattr(fileno(stdin), TCSAFLUSH, &amp;save_buf);
}
</pre></div>




<div class="indented">
<pre>
/* Gtk-based REPL using s7_begin_hook 
 */
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;gtk/gtk.h&gt;

#if HAVE_GTK_3
  #include &lt;gdk/gdk.h&gt;
  #define Return_Key GDK_KEY_Return
  #define C_Key GDK_KEY_C
  #define c_Key GDK_KEY_c
#else
  #include &lt;gdk/gdkkeysyms.h&gt;
  #define Return_Key GDK_Return
  #define C_Key GDK_C
  #define c_Key GDK_c
#endif

#include "s7.h"

#define S7_PROMPT "s7&gt; "
#define S7_PROMPT_LENGTH 4
#define S7_INTERRUPTED_MESSAGE "\ns7 interrupted!"

static GtkWidget* repl;                        /* the REPL text widget */
static GtkTextBuffer *repl_buf;                /* its text buffer */
static GtkTextTag *prompt_not_editable = NULL; /* a tag to make sure the prompt can't be erased */
static GdkCursor *arrow, *spinner;

static gint quit_repl(GtkWidget *w, GdkEvent *event, gpointer context) {exit(0);}

<em class=red>static bool C_c_typed = false;

static void begin_hook(s7_scheme *sc, bool *result)
{
  C_c_typed = false;
  if (gtk_events_pending()) /* this is very slow &mdash; see snd-listener.c for a work-around */
    gtk_main_iteration();
  *result = C_c_typed;
}</em>

static void evaluate_expression(s7_scheme *sc, char *expression)
{
  /* evaluate expression, display result, catching and displaying any errors */
  if ((expression) &amp;&amp;
      (*expression))
    {
      if ((strlen(expression) &gt; 1) || 
	  (expression[0] != '\n'))
	{
	  const char *errmsg = NULL;
	  int gc_loc;
	  s7_pointer old_port, result;
	  GtkTextIter pos;

	  old_port = s7_set_current_error_port(sc, s7_open_output_string(sc));
	  gc_loc = s7_gc_protect(sc, old_port);
	  gdk_window_set_cursor(gtk_text_view_get_window(GTK_TEXT_VIEW(repl), GTK_TEXT_WINDOW_TEXT), spinner);
	  
	  <em class=red>s7_set_begin_hook(sc, begin_hook);
	  result = s7_eval_c_string(sc, expression);
	  s7_set_begin_hook(sc, NULL);</em>

	  gdk_window_set_cursor(gtk_text_view_get_window(GTK_TEXT_VIEW(repl), GTK_TEXT_WINDOW_TEXT), arrow);
	  gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);

	  <em class=red>if (C_c_typed)
	    {
	      gtk_text_buffer_insert(repl_buf, &amp;pos, S7_INTERRUPTED_MESSAGE, strlen(S7_INTERRUPTED_MESSAGE));
	      C_c_typed = false;
	    }
	  else</em>
	    {
	      errmsg = s7_get_output_string(sc, s7_current_error_port(sc));
	      if ((errmsg) &amp;&amp; (*errmsg))
		gtk_text_buffer_insert(repl_buf, &amp;pos, errmsg, strlen(errmsg));
	      else 
		{
		  char *result_as_string;
		  result_as_string = s7_object_to_c_string(sc, result);
		  if (result_as_string)
		    {
		      gtk_text_buffer_insert(repl_buf, &amp;pos, "\n", 1);
		      gtk_text_buffer_insert(repl_buf, &amp;pos, result_as_string, strlen(result_as_string));
		      free(result_as_string);
		    }
		}
	    }

	  s7_close_output_port(sc, s7_current_error_port(sc));
	  s7_set_current_error_port(sc, old_port);
	  s7_gc_unprotect_at(sc, gc_loc);
	}

      g_free(expression);
    }
}

static char *get_current_expression(void)
{
  GtkTextIter pos, previous, next, temp;
  GtkTextMark *m;
  m = gtk_text_buffer_get_insert(repl_buf);
  gtk_text_buffer_get_iter_at_mark(repl_buf, &amp;pos, m);
  if (gtk_text_iter_backward_search(&amp;pos, S7_PROMPT, 0, &amp;temp, &amp;previous, NULL))
    {
      if (!gtk_text_iter_forward_search(&amp;pos, S7_PROMPT, 0, &amp;next, &amp;temp, NULL))
	{
	  gtk_text_buffer_get_end_iter(repl_buf, &amp;next);
	  return(gtk_text_buffer_get_text(repl_buf, &amp;previous, &amp;next, true));
	}
      gtk_text_iter_backward_search(&amp;next, "\n", 0, &amp;pos, &amp;temp, NULL);     
      gtk_text_iter_backward_search(&amp;pos, "\n", 0, &amp;next, &amp;temp, NULL);      
      return(gtk_text_buffer_get_text(repl_buf, &amp;previous, &amp;next, true));
    }
  return(NULL);
}

static void prompt(GtkWidget *w)
{
  GtkTextIter pos;
  gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);
  gtk_text_buffer_insert_with_tags(repl_buf, &amp;pos, "\n" S7_PROMPT, 1 + S7_PROMPT_LENGTH, prompt_not_editable, NULL);
  gtk_text_buffer_place_cursor(repl_buf, &amp;pos);
  gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(repl), gtk_text_buffer_get_insert(repl_buf));
  g_signal_stop_emission((gpointer)w, g_signal_lookup("key_press_event", G_OBJECT_TYPE((gpointer)w)), 0);
}

static gboolean repl_key_press(GtkWidget *w, GdkEventKey *event, gpointer scheme)
{
  /* called when you type anything in the text widget.
   */
  guint key, state;
  s7_scheme *sc;

  sc = (s7_scheme *)scheme;
  key = event-&gt;keyval;
  state = event-&gt;state;

  if (key == Return_Key)
    {
      if (<em class=red>s7_begin_hook(sc) == NULL</em>)
	{
	  evaluate_expression(sc, get_current_expression());
	  prompt(w);
	}
    }

  if (((key == C_Key) || (key == c_Key)) &amp;&amp;
      ((state &amp; GDK_CONTROL_MASK) != 0))
    <em class=red>C_c_typed = true</em>;

  return(false);
}

int main(int argc, char **argv)
{
  GtkWidget *shell, *scrolled_window;
  GtkTextIter pos;
  s7_scheme *s7;

  s7 = s7_init();  

  gtk_init(&amp;argc, &amp;argv);
  spinner = gdk_cursor_new(GDK_WATCH);
  arrow = gdk_cursor_new(GDK_LEFT_PTR);
  
  shell = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(G_OBJECT(shell), "delete_event", G_CALLBACK(quit_repl), NULL);

  scrolled_window = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_container_add(GTK_CONTAINER(shell), scrolled_window);

  repl = gtk_text_view_new();
  repl_buf = gtk_text_buffer_new(NULL);
  gtk_container_add(GTK_CONTAINER(scrolled_window), repl);

  gtk_text_view_set_buffer(GTK_TEXT_VIEW(repl), repl_buf);
  gtk_text_view_set_editable(GTK_TEXT_VIEW(repl), true);
  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(repl), GTK_WRAP_NONE);
  gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(repl), true);
  gtk_text_view_set_left_margin(GTK_TEXT_VIEW(repl), 4);
  gtk_widget_set_events(repl, GDK_ALL_EVENTS_MASK);
  g_signal_connect(G_OBJECT(repl), "key_press_event", G_CALLBACK(repl_key_press), (void *)s7);

  gtk_widget_show(repl);
  gtk_widget_show(scrolled_window);
  gtk_widget_show(shell);

  prompt_not_editable = gtk_text_buffer_create_tag(repl_buf, "prompt_not_editable", 
						   "editable", false, 
						   "weight", PANGO_WEIGHT_BOLD,
						   NULL);
  gtk_text_buffer_get_end_iter(repl_buf, &amp;pos);
  gtk_text_buffer_insert_with_tags(repl_buf, &amp;pos, S7_PROMPT, S7_PROMPT_LENGTH, prompt_not_editable, NULL);
  gdk_window_resize(gtk_widget_get_window(shell), 400, 200);
  gtk_main();
}
</pre></div>


<p>In the Gtk case above, begin_hook itself checks the user-interface (via gtk_main_iteration), so a key_press event
(or any other) can still get through, even if s7_eval_c_string falls into an
infinite loop.  If a GUI event triggers a call on s7, that call happens in the current thread
at a protected point in the s7 evaluation, so the GUI toolkit is happy because there's
only the current thread, and s7 is happy because it handles the interleaved expression
at a point where it can't confuse the current evaluation.
If the begin_hook function sets its bool argument to true (if C-C is typed),
s7 itself calls s7_quit, interrupting the current evaluation. 
If the user types return, and s7 is running (begin_hook is not NULL),
we ignore it.  Otherwise return causes our REPL to send
the current string to s7_eval_c_string.  Upon returning from s7_eval_c_string,
we check whether we were interrupted (C_c_typed is true), and if so, send a surprised
message to the REPL.  Otherwise we handle everything as in the previous REPLs.
</p>

<p>If the s7 evaluation can't affect the GUI and the GUI can't call s7 itself,
then you don't need to use begin_hook.
</p>

<p>begin_hook provides a way to call arbitrary C or Scheme code at any time;
the mind boggles!  
</p>

<p>Since the normal
begin_hook function keeps the interface alive, a callback can save the current
begin_hook function, insert its own function to do something useful, then that function can
replace itself with the original:
</p>


<div class="indented">
<pre>
static void (*current_begin_hook)(s7_scheme *sc, bool *val); /* this will be the saved original function */

static void stacktrace_begin_hook(s7_scheme *sc, bool *val)  /* this is our one-shot replacement */
{
  fprintf(stderr, "%s\n", s7_string(s7_stacktrace(sc)));     /* it prints local var info */
  s7_set_begin_hook(s7, current_begin_hook);                 /*   then replaces itself with the original */
}

static void listener_stacktrace_callback(...)                /* the usual callback boilerplate here */
{
  current_begin_hook = s7_begin_hook(s7);                    /* save current begin_hook function */
  if (current_begin_hook)                                    /* s7 is running, so... */
    s7_set_begin_hook(s7, stacktrace_begin_hook);            /*   insert our stacktrace function in its place */
}
</pre></div>



<div class="header" id="glistener"><h4>glistener.c</h4></div>

<p>glistener.c is a gtk-based repl.  It is not specific to s7:
Snd uses it as its Forth and Ruby listener as well as for s7.  
Here's a short example:
</p>

<div class="indented">
<pre>
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdbool.h&gt;

#include &lt;gtk/gtk.h&gt;

#include "s7.h"
#include "glistener.h"

static s7_scheme *s7;

static gint quit_repl(GtkWidget *w, GdkEvent *event, gpointer context) {exit(0);}

static void evaluator(glistener *g, const char *text)
{
  /* this sends "text" to s7 for evaluation, then displays the result */
  int gc_loc;
  s7_pointer old_port, result;
  const char *errmsg = NULL;
  char *msg = NULL;
  
  old_port = s7_set_current_error_port(s7, s7_open_output_string(s7));
  gc_loc = s7_gc_protect(s7, old_port);
  
  result = s7_eval_c_string(s7, text);
  errmsg = s7_get_output_string(s7, s7_current_error_port(s7));
  if ((errmsg) && (*errmsg))
    {
      msg = (char *)calloc(strlen(errmsg) + 1, sizeof(char));
      strcpy(msg, errmsg);
    }
  
  s7_close_output_port(s7, s7_current_error_port(s7));
  s7_set_current_error_port(s7, old_port);
  s7_gc_unprotect_at(s7, gc_loc);
  
  glistener_append_text(g, "\n");
  if (msg)                      /* some error occurred during evaluation */
    glistener_append_text(g, msg);
  else 
    {                           /* evaluation produced an s7 object which we need to display */
      msg = s7_object_to_c_string(s7, result);
      glistener_append_text(g, msg);
    }
  if (msg) free(msg);
  glistener_append_prompt(g);  /* prompt for more input */
}

static void listener_init(glistener *g, GtkWidget *w)
{
  /* this is the glistener initialization function. "w" above is the new text-view widget,
   *   "g" is the new glistener pointer, passed to any function that wants to talk to this
   *   listener. 
   */
  unsigned char prompt[4] = {0xce, 0xbb, '&gt;', '\0'}; /* lambda as prompt */
  GtkTextBuffer *buffer;

  buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(w));
  glistener_set_font(g, pango_font_description_from_string("Monospace 10"));

  /* our prompt will be a red lambda */
  glistener_set_prompt_tag(g, gtk_text_buffer_create_tag(buffer, "glistener_prompt_tag", 
							 "weight", PANGO_WEIGHT_BOLD, 
							 "foreground", "red",
							 NULL));
  glistener_set_prompt(g, prompt);
}

static const char *helper(glistener *g, const char *text)
{
  /* this function is called whenever the listener thinks help is needed.
   *   Any string it returns is posted in the listener statusbar.
   */
  s7_pointer sym;
  sym = s7_symbol_table_find_name(s7, text);
  if (sym)
    return(s7_help(s7, sym));
  glistener_clear_status(g);
  return(NULL);
}

static void completer(glistener *g, bool (*symbol_func)(const char *symbol_name, void *data), void *data)
{
  /* this function is called when &lt;tab&gt; is typed after a partial symbol name. 
   *   "symbol_func" above should be called on each member of the symbol-table, passing it
   *   the symbol name (as a string) and the data passed as "completer's" third argument.
   *   If symbol_func returns true, it is done, so the loop through the symbol-table can stop.
   */
  s7_for_each_symbol_name(s7, symbol_func, data);
}

int main(int argc, char **argv)
{
  GtkWidget *shell, *frame;
  glistener *g;

  s7 = s7_init();  

  gtk_init(&amp;argc, &amp;argv);
  shell = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(G_OBJECT(shell), "delete_event", G_CALLBACK(quit_repl), NULL);

  frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_ETCHED_IN);
  gtk_widget_show(frame);

  gtk_container_add(GTK_CONTAINER(shell), frame);

  /* make a new listener */
  g = glistener_new(frame, listener_init);
  glistener_set_evaluator(g, evaluator);
  glistener_set_helper(g, helper);
  glistener_set_completer(g, completer);

  gtk_widget_show(shell);
  gdk_window_resize(gtk_widget_get_window(shell), 400, 200);
  gtk_main();
}

/* in gtk-2: gcc gcall.c -o gcall s7.o glistener.o `pkg-config --libs gtk+-2.0 --cflags` -lm -ldl
 * in gtk-3: gcc gcall.c -o gcall s7.o glistener.o `pkg-config --libs gtk+-3.0 --cflags` -lm -ldl
 */
</pre>

<div class="listener">
<pre>
<em class=redb>&lambda;&gt;</em> (define &lambda; lambda)
&lambda;
<em class=redb>&lambda;&gt;</em> ((&lambda; (a b) (+ a b)) 1 2)
3
<em class=redb>&lambda;&gt;</em> 
</pre>
</div>

<br>
<p>The five or six functions supplied by the caller (evaluator, helper, 
completer, checker, colorizer, keyer) all have defaults, so you don't have to supply
anything but an evaluator.  The default evaluator just prints "?" and prompts
for more input.  See glistener.h for the full API and an earnest attempt
at helpful documentation.
</p>

<p>A multi-listener test program is the Snd file tools/gcall.c which
is used by tools/gtest.scm for regression testing. One way to name unicode characters
is: <code>(define-constant |lambda| #u8(#xce #xbb))</code>.  This can be embedded
in an ordinary s7 string with any string operation: <code>(string-append |lambda| "ambda")</code>
which returns "&lambda;ambda".  (string-length will still return the number of bytes; to get
the number of characters in a case like this, use g_utf8_strlen).
So, to set the prompt to be a red lambda and the font to be "Nimbus mono 10" from Scheme,
assuming we have the usual Scheme-to-C linkages (see snd-glistener.c):
</p>

<pre class="indented">
(set! (listener-prompt) (bytevector #xce #xbb (char-&gt;integer #\&gt;) (char-&gt;integer #\space)))
(set! (listener-font) "Nimbus mono 10")
(listener-set-prompt-tag *listener* ; ideally this too would be a setter
  (gtk_text_buffer_create_tag 
    (GTK_TEXT_BUFFER (gtk_text_view_get_buffer (GTK_TEXT_VIEW (listener-text-widget *listener*))))
    "" (list "weight" PANGO_WEIGHT_BOLD "foreground" "red")))
</pre>
</div>


<div class="header" id="gdb"><h4>gdb</h4></div>

<p>It is possible to make a mistake while writing C code.
I switched from Common Lisp to Scheme a long time ago
partly because it was so painful to debug FFI troubles in Common Lisp, and I
chose Guile at that time partly because I thought gdb would have native support
for it.  As far as I know it is still impossible to debug CL FFI troubles, 20 years later!
And in gdb Python has muscled Guile aside.  Anyway, say you have hit a segfault
and find yourself staring at a stackful of opaque pointers.  Print statements are your
friend, of course, and at the gdb command level, the main one in this context is
s7_object_to_c_string.  Here are some commands (intended for your .gdbinit file)
that can speed up the process.  They assume the s7_scheme pointer is named "sc".
</p>

<pre class="indented">
define s7print
print s7_object_to_c_string(sc, $arg0)
end
document s7print
interpret the argument as an s7 value and display it
end
# the current expression is sc-&gt;cur_code
# the current environment is sc-&gt;envir
# the error environment is sc-&gt;error_env
# so for example, to see the current local variables, s7p sc-&gt;envir

define s7eval
print s7_object_to_c_string(sc, s7_eval_c_string(sc, $arg0))
end
document s7eval
eval the argument (a string)
end

define s7stack
print s7_object_to_c_string(sc, s7_stacktrace(sc))
end
document s7stack
display the current stack
end

define s7value
print s7_object_to_c_string(sc, s7_name_to_value(sc, $arg0))
end
document s7value
print the value of the variable passed by its print name: s7v "*features*"
end
</pre>

<br><br>


<div class="topheader" id="s7examples">s7 examples</div>

<p>The s7 tarball includes several scheme files including s7test.scm,
lint.scm, and cload.scm.  s7test.scm is a regression test for s7, lint.scm
is the s7 equivalent of the ancient C program named lint, and cload.scm
is a wrapper for the FFI stuff described above.
</p>


<div class="header" id="lint"><h4>lint.scm</h4></div>

<p>lint tries to find errors or infelicities in your scheme code.
To try  it:
</p>

<pre class="indented">
(load "lint.scm")
(lint "some-code.scm")
</pre>


<p>lint tries to reduce false positives, so its default behavior is somewhat laconic.  There are several
variables at the start of lint.scm to control additional output:
</p>


<pre class="indented">
*report-unused-parameters*           ; if #t, report unused function/macro parameters
*report-unused-top-level-functions*  ; if #t, report unused functions
*report-undefined-variables*         ; if #t, report undefined identifiers
*report-shadowed-variables*          ; if #t, report function parameters that are shadowed
*report-minor-stuff*                 ; if #t, report all sorts of other stuff
</pre>


<p>lint is not smart about functions defined outside the current file, so *report-undefined-variables*
sometimes gets confused.  *report-minor-stuff* adds output about overly complicated boolean and numerical
expressions, dangerous floating point operations, bad docstrings (this check can get confused), and
whatever else it thinks is odd.
</p>

<p>Also in lint.scm is html-lint.  It reads an HTML file looking for
Scheme code.  If any is found, it runs s7 and then lint over it, reporting troubles.
</p>



<div class="header" id="cload"><h4>cload.scm</h4></div>

<p>cload.scm defines the macro c-define that reduces the overhead
involved in (dynamically) linking C entities into s7.
</p>

<pre class="indented">
(<em class=def id="definecfunction">c-define</em> c-info (prefix "") (headers ()) (cflags "") (ldflags "") output-name)
</pre>

<p>For example, <code>(c-define '(double j0 (double)) "m" "math.h")</code>
links the C math library function j0 into s7 under the name m:j0, 
passing it a double argument and getting a double result (a real in s7).
</p>

<p><em>prefix</em> is some arbitrary prefix that you want prepended to various names.
</p>

<p><em>headers</em> is a list of headers (as strings) that the c-info relies on, (("math.h") for example).
</p>

<p><em>cflags</em> are any special C compiler flags that are needed ("-I." in particular), and
<em>ldflags</em> is the similar case for the loader.  <em>output-name</em> is the name of the
output C file and associated library.  It defaults to "temp-s7-output" followed by a number.
In libm.scm, it is set to "libm_s7" to protect it across cload calls.  If cload finds an
up-to-date output C file and shared library, it simply loads the library, rather than
going through all the trouble of writing and compling it.
</p>

<p><em>c-info</em> is a list that describes the C entities that you want to load into s7.
It can be either one list describing one entity, or a list of such lists.
Each description has the form:
</p>

<pre class="indented">
(return-type entity-name-in-C (argument-type...))
</pre>

<p>where each entry is a symbol, and C names are used throughout.  So, in the j0
example above, <code>(double j0 (double))</code> says we want access to j0, it returns
a C double, and it takes one argument, also a C double.  s7 tries to figure out 
what the corresponding s7 type is, but in tricky cases, you should tell it
by replacing the bare type name with a list: <code>(C-type underlying-C-type)</code>.  For example,
the Snd function set_graph_style takes an (enum) argument of type graph_style_t.
This is actually an int, so we use <code>(graph_style_t int)</code> as the type:
</p>

<pre class="indented">
(void set_graph_style ((graph_style_t int)))
</pre>

<p>If the C entity is a constant, then the descriptor list has just two entries,
the C-type and the entity name: <code>(int F_OK)</code> for example. The entity name can also be a list:
</p>

<pre class="indented">
((graph_style_t int) (GRAPH_LINES GRAPH_DOTS GRAPH_FILLED GRAPH_DOTS_AND_LINES GRAPH_LOLLIPOPS))
</pre>

<p>This defines all the names in the list as integers.
If the C type has a space ("struct tm*"), use <code>(symbol "struct tm*")</code>
to construct the corresponding symbol.
</p>

<p>The entity is placed in the current s7 environment under the name <code>(string-append prefix ":" name)</code>
where the ":" is omitted if the prefix is null.  So in the j0 example, we get in s7 the function m:j0.
c-define returns #t if it thinks the load worked, and #f otherwise.
</p>

<p>There are times when the only straightforward approach is to write the desired
C code directly.  To insert C code on the fly, use (in-C "code..."). Two more such
cases that come up all the time: C-function for linkage to functions written
directly in s7 style using in-C, and C-macro for macros in the C header file that
need to be wrapped in #ifdefs.
Here are some examples:
</p>

<pre class="indented">
;;; various math library functions
(c-define '((double j0 (double)) 
            (double j1 (double)) 
            (double erf (double)) 
            (double erfc (double))
            (double lgamma (double)))
          "m" "math.h")


;;; getenv and setenv
(c-define '(char* getenv (char*)))
(c-define '(int setenv (char* char* int)))


;;; file-exists? and delete-file
(define file-exists? (let () ; define F_OK and access only within this let
                       (c-define '((int F_OK) (int access (char* int))) "" "unistd.h") 
                       (lambda (arg) (= (access arg F_OK) 0))))

(define delete-file (let () 
                      (c-define '(int unlink (char*)) "" "unistd.h") 
                      (lambda (file) (= (unlink file) 0)))) ; 0=success


;;; examples from Snd:
(c-define '(char* version_info ()) "" "snd.h" "-I.")

(c-define '(mus_float_t mus_degrees_to_radians (mus_float_t)) "" "snd.h" "-I.")

(c-define '(snd_info* any_selected_sound ()) "" "snd.h" "-I.")
(c-define '(void select_channel (snd_info* int)) "" "snd.h" "-I.")

(c-define '(((graph_style_t int) (GRAPH_LINES GRAPH_DOTS GRAPH_FILLED GRAPH_DOTS_AND_LINES GRAPH_LOLLIPOPS)) 
            (void set_graph_style ((graph_style_t int)))) 
          "" "snd.h" "-I.")
   

;;; getcwd, strftime
(c-define '(char* getcwd (char* size_t)) "" "unistd.h")

(c-define (list '(void* calloc (size_t size_t))
	        '(void free (void*))
	        '(void time (time_t*)) ; ignore returned value
	        (list (symbol "struct tm*") 'localtime '(time_t*))
                (list 'size_t 'strftime (list 'char* 'size_t 'char* (symbol "struct tm*"))))
          "" "time.h")

&gt; (let ((p (calloc 1 8)) 
        (str (make-string 32)))
    (time p) 
    (strftime str 32 "%a %d-%b-%Y %H:%M %Z" (localtime p))
    (free p) 
    str)
"Sat 11-Aug-2012 08:55 PDT\x00      "


;;; opendir, read_dir, closedir
(c-define '((int closedir (DIR*))
	    (DIR* opendir (char*))
	    (in-C "static char *read_dir(DIR *p)  \
                   {                              \
                     struct dirent *dirp;          \
                     dirp = readdir(p);            \
                     if (!dirp) return(NULL);      \
                     return(dirp-&gt;d_name);         \
                   }")
	    (char* read_dir (DIR*)))
  "" '("sys/types.h" "dirent.h"))

(let ((dir (opendir "/home/bil/gtk-snd")))
  (do ((p (read_dir dir) (read_dir dir)))
      ((= (length p) 0))
    (format *stderr* "~A " p))
  (closedir dir))
</pre>


<p>For the simple cases above, include "-ldl -Wl,-export-dynamic" in the gcc command.  So the first
FFI example is built (this is in Linux):
</p>

<pre class="indented">
gcc -c s7.c -I.
gcc -o ex1 ex1.c s7.o -lm -I. -ldl -Wl,-export-dynamic
ex1
&gt; (load "cload.scm")
c-define-1
&gt; (c-define '(double j0 (double)) "m" "math.h")
#t
&gt; (m:j0 0.5)
0.93846980724081
</pre>

<p>See also r7rs.scm, libc.scm, libgsl.scm, libm.scm, libdl.scm, and libgdbm.scm.
</p>

</body>
</html>


<!--
circular env without set!: 
(let ()
   (let ((b (current-environment)))
      (current-environment)))

circular func (implicit set!):
(letrec* ((b (lambda () (a)))
	  (a (lambda () (b))))
  (a))

(letrec ((b (lambda () (a)))
	 (a (lambda () (b))))
  (a))
-->

